开发者

C# divide two binary numbers

开发者 https://www.devze.com 2022-12-21 20:56 出处:网络
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

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.


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


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


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


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


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();
        }
        }
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号