Int to byte array
Solution 1:
Update for 2020 - BinaryPrimitives
should now be preferred over BitConverter
. It provides endian-specific APIs, and is less allocatey.
byte[] bytes = BitConverter.GetBytes(i);
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.
Solution 2:
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.
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit)]
struct Int32Converter
{
[FieldOffset(0)] public int Value;
[FieldOffset(0)] public byte Byte1;
[FieldOffset(1)] public byte Byte2;
[FieldOffset(2)] public byte Byte3;
[FieldOffset(3)] public byte Byte4;
public Int32Converter(int value)
{
Byte1 = Byte2 = Byte3 = Byte4 = 0;
Value = value;
}
public static implicit operator Int32(Int32Converter value)
{
return value.Value;
}
public static implicit operator Int32Converter(int value)
{
return new Int32Converter(value);
}
}
The above can now be used as follows
Int32Converter i32 = 256;
Console.WriteLine(i32.Byte1);
Console.WriteLine(i32.Byte2);
Console.WriteLine(i32.Byte3);
Console.WriteLine(i32.Byte4);
i32.Byte2 = 2;
Console.WriteLine(i32.Value);
Of course the immutability police may not be excited about the last possiblity :)
Solution 3:
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.
Solution 4:
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.