Re: Display an int in Binary
Re: Display an int in Binary
The result is simple like
Code:
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:
Re: Display an int in Binary
Quote:
Originally Posted by
siulung
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
Code:
// 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);
Re: Display an int in Binary
thx a lot , just what i am looking for.