Create an array of bytes from a set of integers

Given these integers:

public uint ServerSequenceNumber; public uint Reserved1; public uint Reserved2; public byte Reserved3; public byte TotalPlayers; 

What is the best way to create a byte[] array? If all of their values ​​are 1 , the resulting array will be:

 00000000000000000000000000000001 00000000000000000000000000000001 00000000000000000000000000000001 00000001 00000001 
+6
source share
3 answers

This should do what you are looking for. BitConverter returns an array of bytes in order of continuation of the processor used. For x86-processors this is of little use. This first puts the least significant byte.

  int value; byte[] byte = BitConverter.GetBytes(value); Array.Reverse(byte); byte[] result = byte; 

If you do not know the processor that you intend to use the application, I suggest using:

 int value; byte[] bytes = BitConverter.GetBytes(value); if (BitConverter.IsLittleEndian){ Array.Reverse(bytes); } byte[] result = bytes; 
+7
source

Like this?

 byte[] bytes = new byte[14]; int i = 0; foreach(uint num in new uint[]{SecureSequenceNumber, Reserved1, Reserved2}) { bytes[i] = (byte)(num >> 24); bytes[i + 1] = (byte)(num >> 16); bytes[i + 2] = (byte)(num >> 8); bytes[i + 3] = (byte)num; i += 4; } bytes[12] = Reserved3; bytes[13] = TotalPlayers; 
+2
source

Turning around @Robert's answer, I created a simple class that makes things tidier when you do a lot of concatenations:

 class ByteJoiner { private int i; public byte[] Bytes { get; private set; } public ByteJoiner(int totalBytes) { i = 0; Bytes = new byte[totalBytes]; } public void Add(byte input) { Add(BitConverter.GetBytes(input)); } public void Add(uint input) { Add(BitConverter.GetBytes(input)); } public void Add(ushort input) { Add(BitConverter.GetBytes(input)); } public void Add(byte[] input) { System.Buffer.BlockCopy(input, 0, Bytes, i, input.Length); i += input.Length; } } 
+1
source

All Articles