我需要把int
换成byte[]
,一种方法是用BitConverter.GetBytes()
.但我不确定这是否符合以下规范:
XDR带符号整数是一个32位的数据,它在
来源:RFC1014 3.2
我如何进行int到byte的转换以满足上述规范?
我需要把int
换成byte[]
,一种方法是用BitConverter.GetBytes()
.但我不确定这是否符合以下规范:
XDR带符号整数是一个32位的数据,它在
来源:RFC1014 3.2
我如何进行int到byte的转换以满足上述规范?
RFC只是想说一个有符号整数是一个普通的4字节整数,字节以大端排序.
现在,你很可能在一台小小的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;