整数到字节数组 [英] 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!
请注意,如果您反复进行 ,您可能希望通过任何一次移位操作(>>
/ << ;
),或使用不安全
代码。移位操作还的优点是不受平台的字节序影响;您总是按期望的顺序获取字节。
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屋!