Reputation: 6226
I would like to convert a byte to a string.
Example:
byte testByte = 0x05;
testByte should be converted to "00000101"
I have tried Convert.ToString(testByte, 2), but it only returns "101"
Upvotes: 4
Views: 307
Reputation: 78312
static string ToBase2String(int n, int pad)
{
var s = n < 0 ? "-" : "";
var v = n < 0 ? -n : n;
while (v > 0)
{
s = (v % 2 == 0 ? "0" : "1") + s;
v /= 2;
}
return s.PadLeft(pad, '0');
}
Upvotes: -1
Reputation: 983
You're pretty close already all you need to do is call PadLeft
on the resulting String
that you have already:
Convert.ToString(testByte, 2).PadLeft(8,'0');
Upvotes: 4