内容目录
// 二进制位数长度
private int binaryLength = 16;
// 将数字转为 N 位二进制,并且前面补足 0
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($"数字二进制长度超过{binaryLength}位!");
for (int i = str.Length - 1; i >= 0; i--)
{
n--;
bs[n] = str[i].Equals('1') ? (byte)1 : (byte)0;
}
//补足位数,前缀加上0
for (int i = n - 1; i >= 0; i--)
{
bs[i] = 0;
}
return bs;
}
文章评论