Compute how many bits to require convert one integer to another

来源:互联网 发布:mac win8压缩软件 编辑:程序博客网 时间:2024/06/04 09:01
Problem
Write a function to determine the number of bits required to convert integer A to integer B.
Input: 31, 14
Output: 2

Solution

using System;

namespace JamesChen
{
    class BitDifference
    {
        static int CalculateBitDifference(int a, int b)
        {
            int count = 0;
            a = a ^ b;
            while (a != 0)
            {
                a &= (a - 1);
                count++;
            }

            return count;
        }

        static void DoTest(int a, int b)
        {
            Console.WriteLine("a = {0, 4}, b = {1, 4}", a, b);
            Console.WriteLine("{0, 32} -- a", Convert.ToString(a, 2));
            Console.WriteLine("{0, 32} -- b", Convert.ToString(b, 2));
            Console.WriteLine("requires {0} bit convert a to b",
                CalculateBitDifference(a, b));
            Console.WriteLine("-----------------------------------");
        }

        static void Main(string[] args)
        {
            DoTest(31, 14);
            DoTest(14, 31);
            DoTest(-2, 0);
            DoTest(0, -2);
            DoTest(-5, -20);
            DoTest(-20, -5);
        }
    }
}

Output
a =   31, b =   14
                           11111 -- a
                            1110 -- b
requires 2 bit convert a to b
-----------------------------------
a =   14, b =   31
                            1110 -- a
                           11111 -- b
requires 2 bit convert a to b
-----------------------------------
a =   -2, b =    0
11111111111111111111111111111110 -- a
                               0 -- b
requires 31 bit convert a to b
-----------------------------------
a =    0, b =   -2
                               0 -- a
11111111111111111111111111111110 -- b
requires 31 bit convert a to b
-----------------------------------
a =   -5, b =  -20
11111111111111111111111111111011 -- a
11111111111111111111111111101100 -- b
requires 4 bit convert a to b
-----------------------------------
a =  -20, b =   -5
11111111111111111111111111101100 -- a
11111111111111111111111111111011 -- b
requires 4 bit convert a to b
-----------------------------------
Press any key to continue . . .
原创粉丝点击