Monday, January 29, 2007

Convert Integer to Binary, Binary to Integer

Problem:
Convert integer to binary string

int binary
15 1111



Convert binary string to integer
binary int
1111 15



Solution:

//Convert binary string to an integer
int a_integer = Convert.ToInt32("1111", 2);

//convert an integer to a binary string
string a_binary_string = Convert.ToString(a_integer, 2);


Information:

How does the binary string "1111" equal 15

First, and most important, binary is read "right to left"

Second, each place holder position is 2^(position), zero position based
example:

(2^0)=1

if(a binary digit is 1) add to total

"1111" = (2^3) + (2^2) + (2^1) +(2^0)
^ -----
^
^
^ ------- ---- ---- ----
(2*2*2) (2*2) (2) (1)

8 + 4 + 2 + 1

= 15


"0010" = (0) + (0) + (2^1) + (0)
0 + 0 + 2 + 0

= 2

No comments: