Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create byte array from set of integers

Given these integers:

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

What's the best way to create a byte[] array from them? If all their values are 1 the resulting array would be:

00000000000000000000000000000001 00000000000000000000000000000001 00000000000000000000000000000001 00000001 00000001
like image 463
Tom Gullen Avatar asked Jan 22 '13 16:01

Tom Gullen


People also ask

How do I convert an integer to a byte array?

When you want to convert an int value to a byte array, you can use the static method ByteArray. toByteArray(). This method takes an int input and returns a byte array representation of the number.

How do you assign a byte array?

We can use String class getBytes() method to encode the string into a sequence of bytes using the platform's default charset. This method is overloaded and we can also pass Charset as argument.

How do you create a byte array in java?

In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file. Example: Java.

What is a byte [] in C#?

In C#, Byte Struct is used to represent 8-bit unsigned integers. The Byte is an immutable value type and the range of Byte is from 0 to 255. This class allows you to create Byte data types and you can perform mathematical and bitwise operations on them like addition, subtraction, multiplication, division, XOR, AND etc.


1 Answers

This should do what your looking for. BitConverter returns a byte array in the order of endianness of the processor being used. For x86 processors it is little-endian. This places the least significant byte first.

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

If you don't know the processor your going to be using the app on I suggest using:

int value;
byte[] bytes = BitConverter.GetBytes(value);
if (BitConverter.IsLittleEndian){
Array.Reverse(bytes);
}
byte[] result = bytes;
like image 178
Robert Avatar answered Sep 22 '22 10:09

Robert