[RESOLVED] Converting a long to a bit string
Hi. I've got to access a set of user permissions. There are 32 possible permissions that can be either true or false. The function that gets the permissions returns a long. Each bit in that long (from 0-31) represents one of the options. What I'd like to do is convert that long to a string of 1's and 0's.
For example, if the number came back as 32 I'd like to convert it to
"00000000 00000000 00000000 00010000"
Thanks.
Re: Converting a long to a bit string
In the meantime I found a function to do what I need. For future reference, here it is:
Code:
public string Int32ToBinary(int integerValue)
{
string returnVal = string.Empty;
int remainder = 0;
for (; integerValue > 0; integerValue /= 2)
{
remainder = integerValue % 2;
returnVal = remainder.ToString() + returnVal;
}
returnVal = returnVal.PadLeft(32, '0');
return returnVal;
}
Thanks.
Re: [RESOLVED] Converting a long to a bit string
Firstly, to convert a number to a binary string you simply do this:
CSharp Code:
myString = Convert.ToString(myNumber, 2);
You can pad that with zeroes if you like, taking note that the long type is 64 bits wide, not 32:
CSharp Code:
myString = Convert.ToString(myNumber, 2).PadLeft(64, '0');
Finally, it would be better to create your own structure for this:
Code:
public struct UserPermissions
{
long value;
public bool this[int index]
{
get
{
if (index < 0 || index > 63)
{
throw new ArgumentOutOfRangeException("index",
index,
"Index values must be within the range 0 to 63 inclusive.");
}
return Convert.ToBoolean(this.value & Convert.ToInt64(Math.Pow(2, index)));
}
set
{
if (index < 0 || index > 63)
{
throw new ArgumentOutOfRangeException("index",
index,
"Index values must be within the range 0 to 63 inclusive.");
}
if (value)
{
this.value |= Convert.ToInt64(Math.Pow(2, index));
}
else
{
this.value &= (long.MaxValue ^ Convert.ToInt64(Math.Pow(2, index)));
}
}
}
public UserPermissions(long value)
{
this.value = value;
}
public long ToInt64()
{
return this.value;
}
}