C# Generate N-bit Binary Number from Integer

2020年5月10日 58点热度 1人点赞 0条评论
内容目录
        // Length of binary bits
        private int binaryLength = 16;
        // Convert number to N-bit binary and pad with 0s at the front
        private byte[] ToBinary(int num)
        {
            byte[] bs = new byte[binaryLength];
            int n = binaryLength;
            char[] str = Convert.ToString(num, 2).ToCharArray();
            if (str.Length > binaryLength)
                throw new ArgumentOutOfRangeException($"The binary length of the number exceeds {binaryLength} bits!");
            for (int i = str.Length - 1; i >= 0; i--)
            {
                n--;
                bs[n] = str[i].Equals('1') ? (byte)1 : (byte)0;
            }
            // Fill in the remaining bits, prefix with 0s
            for (int i = n - 1; i >= 0; i--)
            {
                bs[i] = 0;
            }
            return bs;
        }

痴者工良

高级程序员劝退师

文章评论