ChrisMogz
ChrisMogz

Reputation: 71

C# divide two binary numbers

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.

Upvotes: 6

Views: 4943

Answers (5)

SrividhyaShama
SrividhyaShama

Reputation: 549

This will help u.

 namespace BinaryExample1
        {
        class Program
        {
        static void Main(string[] args)
        {
        int i = Convert.ToInt32("01000100", 2);
        int j = Convert.ToInt32("00000100", 2);
        int z;
        z = i / j;
        Console.WriteLine(z);
        Console.ReadLine();
        }
        }
        }

Upvotes: 0

SwDevMan81
SwDevMan81

Reputation: 49978

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);

Upvotes: 2

Andrey
Andrey

Reputation: 60055

it is just:

x / y

you don't have to convert integer into binary string by

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

numbers are binary in memory.

or i didn't understood you

Upvotes: 2

Thomas Levesque
Thomas Levesque

Reputation: 292345

// 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);

Upvotes: 8

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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

Upvotes: 3

Related Questions