整数到字节数组 [英] Int to byte array
问题描述
我认为 .net 有某种简单的转换方法可用于将 int 转换为字节数组?我进行了快速搜索,所有解决方案都是位掩码/一次移动一个字节,例如美好的时光".某处没有 ToByteArray() 方法吗?
I thought .net had some kind of easy conversion method to use for converting an int into a byte array? I did a quick search and all solutions are bit masking/shifting one byte at a time, like "the good ol days". Is there not a ToByteArray() method somewhere?
推荐答案
2020 年更新 - BinaryPrimitives
现在应该优先于 BitConverter
.它提供特定于字节序的 API,并且分配更少.
Update for 2020 - BinaryPrimitives
should now be preferred over BitConverter
. It provides endian-specific APIs, and is less allocatey.
byte[] bytes = BitConverter.GetBytes(i);
尽管还要注意,您可能想要检查 BitConverter.IsLittleEndian
以查看会出现哪种方式!
although note also that you might want to check BitConverter.IsLittleEndian
to see which way around that is going to appear!
请注意,如果您重复这样做,您可能希望通过任一移位操作(>>
/<<
),或使用 unsafe
代码.Shift 操作还具有不受平台字节序影响的优点;你总是按照你期望的顺序获得字节.
Note that if you are doing this repeatedly you might want to avoid all those short-lived array allocations by writing it yourself via either shift operations (>>
/ <<
), or by using unsafe
code. Shift operations also have the advantage that they aren't affected by your platform's endianness; you always get the bytes in the order you expect them.
这篇关于整数到字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!