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?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
If you came here from Google
Alternative answer to an older question refers to John Skeet's Library that has tools for letting you write primitive data types directly into a byte[] with an Index offset. Far better than
BitConverter
if you need performance.Older thread discussing this issue here
John Skeet's Libraries are here
Just download the source and look at the
MiscUtil.Conversion
namespace.EndianBitConverter.cs
handles everything for you.Update for 2020 -
BinaryPrimitives
should now be preferred overBitConverter
. It provides endian-specific APIs, and is less allocatey.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 usingunsafe
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.Most of the answers here are either 'UnSafe" or not LittleEndian safe. BitConverter is not LittleEndian safe. So building on an example in here (see the post by PZahra) I made a LittleEndian safe version simply by reading the byte array in reverse when BitConverter.IsLittleEndian == true
It returns this:
which is the exact hex that went into the byte array.
Marc's answer is of course the right answer. But since he mentioned the shift operators and unsafe code as an alternative. I would like to share a less common alternative. Using a struct with
Explicit
layout. This is similar in principal to a C/C++union
.Here is an example of a struct that can be used to get to the component bytes of the Int32 data type and the nice thing is that it is two way, you can manipulate the byte values and see the effect on the Int.
The above can now be used as follows
Of course the immutability police may not be excited about the last possiblity :)
This may be OT but if you are serializing a lot of primitive types or POD structures, Google Protocol Buffers for .Net might be useful to you. This addresses the endianness issue @Marc raised above, among other useful features.