easy and fast way to convert an int to binary?

后端 未结 5 2091
[愿得一人]
[愿得一人] 2020-12-01 02:46

What I am looking for is something like PHPs decbin function in C#. That function converts decimals to its representation as a string.

For example, when

5条回答
  •  伪装坚强ぢ
    2020-12-01 03:21

    This is my answer:

        static bool[] Dec2Bin(int value)
        {
            if (value == 0) return new[] { false };
            var n = (int)(Math.Log(value) / Math.Log(2));
            var a = new bool[n + 1];
            for (var i = n; i >= 0; i--)
            {
                n = (int)Math.Pow(2, i);
                if (n > value) continue;
                a[i] = true;
                value -= n;
            }
            Array.Reverse(a);
            return a;
        }
    

    Using Pow instead of modulo and divide so i think it's faster way.

提交回复
热议问题