Click to See Complete Forum and Search --> : Display an int in Binary


siulung
December 13th, 2008, 01:21 PM
Hi ,

This might be simple , i just couldn't find out how i do it easily.

I have an int variable , i want to convert into string in binary format

ex.

int number1= 3;

i need the variable (a string) number_binary have the value "00000011" ( with 8 digit with leading zeros.)

where number1 <=127 so range is not a problem.

and , as you could probably guess , i need to some what modified the binary value and turn it back to an int , is there any easy way doing this?

Three5Eight
December 13th, 2008, 02:22 PM
Google (http://www.google.com/search?hl=en&q=c%23+int+to+binary&btnG=Search)

Result 1 (http://www.geekpedia.com/tutorial137_Converting-from-decimal-to-binary-and-back.html)

JonnyPoet
December 13th, 2008, 05:16 PM
The result is simple like

int a = 35;
// converting to a string showing binary digits
string result = Convert.ToString(a, 2).PadLeft(8, '0');
// back from a binary sigits string to an integer
int b = Convert.ToInt32(result, 2);

Thats all:wave:

ZOverLord
December 14th, 2008, 11:11 AM
Hi ,

This might be simple , i just couldn't find out how i do it easily.

I have an int variable , i want to convert into string in binary format

ex.

int number1= 3;

i need the variable (a string) number_binary have the value "00000011" ( with 8 digit with leading zeros.)

where number1 <=127 so range is not a problem.

and , as you could probably guess , i need to some what modified the binary value and turn it back to an int , is there any easy way doing this?

Safer and smaller way to store and convert these values in case number1 > 8 bits



// Why use int when you know the number will not ever exceed an 8 bit value, use byte or sbyte instead.

sbyte number1 = 3;

string binary8 = Convert.ToString(number1, 2).PadLeft(8, '0');

// Convert Binary String Back to signed 8 bits
// Safe way to make sure value never exceeds 8 bit value

sbyte number1 = Convert.Convert.ToSByte(binary8, 2);

//Display sbyte from 8 Bit Binary String
MessageBox.Show("New sbyte:" + number1 + " 8 Bit Binary String:" + binary8);

siulung
December 16th, 2008, 04:40 PM
thx a lot , just what i am looking for.