我需要将int
转换为byte[]
,一种方法是使用BitConverter.GetBytes()
。但我不确定这是否符合以下规范:
XDR带符号整数是对-2147483648,2147483647范围内的整数进行编码的32位基准。整数以二的补码表示法表示。最高有效字节和最低有效字节分别为0和3。整数的声明如下:
来源:RFC1014 3.2
我怎样才能做一个int到byte的转换来满足上面的规范?
发布于 2009-08-23 16:33:01
RFC只是试图说明带符号的整数是一个普通的4字节整数,其中的字节按big-endian方式排序。
现在,您很可能正在使用一台小端机器,BitConverter.GetBytes()
将向您提供与之相反的byte[]
。所以你可以试试:
int intValue;
byte[] intBytes = BitConverter.GetBytes(intValue);
Array.Reverse(intBytes);
byte[] result = intBytes;
但是,为了使代码具有最好的可移植性,您可以这样做:
int intValue;
byte[] intBytes = BitConverter.GetBytes(intValue);
if (BitConverter.IsLittleEndian)
Array.Reverse(intBytes);
byte[] result = intBytes;
发布于 2009-08-23 16:40:40
这里有另一种方法:我们都知道1x字节= 8x位,而且,一个“常规”整数(int32)包含32位(4字节)。我们可以使用>>运算符将位向右移位(>>运算符不改变值)。
int intValue = 566;
byte[] bytes = new byte[4];
bytes[0] = (byte)(intValue >> 24);
bytes[1] = (byte)(intValue >> 16);
bytes[2] = (byte)(intValue >> 8);
bytes[3] = (byte)intValue;
Console.WriteLine("{0} breaks down to : {1} {2} {3} {4}",
intValue, bytes[0], bytes[1], bytes[2], bytes[3]);
发布于 2009-08-23 16:33:09
BitConverter.GetBytes(int)
几乎可以做你想做的事情,除了字节顺序是错误的。
在使用BitConverter.GetBytes
或使用Jon Skeet的EndianBitConverter class之前,可以使用IPAddress.HostToNetwork方法交换整数值中的字节。两种方法在可移植性方面都做了正确的事情(Tm)。
int value;
byte[] bytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(value));
https://stackoverflow.com/questions/1318933
复制相似问题