Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# divide two binary numbers

Tags:

c#

math

binary

Is it possible in C# to divide two binary numbers. All I am trying to do is:

Get integer value into binary format, see below

int days = 68;
string binary = Convert.ToString(days, 2);

but how do you divide the binary numbers? , what format should be used?

01000100 / 000000100 = 4

Little confused any help would be great.

like image 803
ChrisMogz Avatar asked Mar 05 '10 11:03

ChrisMogz


3 Answers

// convert from binary representation
int x = Convert.ToInt32("01000100", 2);
int y = Convert.ToInt32("000000100", 2);

// divide
int z = x / y;

// convert back to binary
string z_bin = Convert.ToString(z, 2);
like image 195
Thomas Levesque Avatar answered Nov 15 '22 11:11

Thomas Levesque


int a = Convert.ToInt32("01000100", 2);
int b = Convert.ToInt32("000000100", 2);
int c = a / b;

and by the way the answer is dec:17 instead of dec:4

like image 3
Darin Dimitrov Avatar answered Nov 15 '22 11:11

Darin Dimitrov


If you are trying to mask the bits together, youll want to use the & Operator

// convert from binary representation
int x = Convert.ToInt32("01000100", 2);
int y = Convert.ToInt32("000000100", 2);

// Bitwise and the values together
int z = x & y; // This will give you 4

// convert back to binary
string z_bin = Convert.ToString(z, 2);
like image 2
SwDevMan81 Avatar answered Nov 15 '22 10:11

SwDevMan81