HOWTO Convert Byte or int to Binary String in C#?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

This should be *so* easy! How do I convert a Byte or int to a binary string representation in C#

In JavaScript, it goes like this for an int:

javascript:(123).toString(2
or
javascript:(0xFE).toString(2

No problem. So, how do I do the same in C#? What simple thing am I missing

CSharpene
 
Greets,

You can use the ToString() method of the Convert class to convert the
value to a string in a different base. The base should be either 2, 8, 10
or 16 for binary, octal, decimal and hexadecimal, respectively:
string bits = Convert.ToString(integerValue,2);

Regards,

Joe
 
int i = 100;
string str = Convert.ToString(i, base); //base = 2, 8,10 or 16

HTH

Raj
 
CSharpener said:
This should be *so* easy! How do I convert a Byte or int to a binary
string representation in C#?

In JavaScript, it goes like this for an int:

javascript:(123).toString(2)
or
javascript:(0xFE).toString(2)

No problem. So, how do I do the same in C#? What simple thing am I
missing?

Convert.ToString (byte, int)

eg

byte b = 231;

string s = Convert.ToString(b, 2);

// s is now "11100111"
 
I knew it had to be that easy and even looked at Convert but missed the obvious

Case closed

Thanks

John
 
Back
Top