int to byte []

  • Thread starter Thread starter steve
  • Start date Start date
S

steve

I'd like to take the value of an int and put the value into a byte array.
Basically the hexidecimal representation of an integer, with out having to
convert the integer to a string and then to a byte.

for example:
int myInt = 800;
// I realize this function doesn't exist but this is what I want to
accomplish
byte[] myByteArray = myInt.GetBytes();
 
Hello,

In C, you can do this using a union. C# doesn't have these, but you can get
the same effect using a struct and controlling the field layout yourself.
For example:

[StructLayout(LayoutKind.Explicit)]
struct IntBytes {
[FieldOffset(0)] public int Integer;
[FieldOffset(0)] public byte Byte0;
[FieldOffset(1)] public byte Byte1;
[FieldOffset(2)] public byte Byte2;
[FieldOffset(3)] public byte Byte3;

public IntBytes(int value) {
Byte0 = Byte1 = Byte2 = Byte3 = 0; //the compiler insists these are
explicitly initialised
Integer = value;
}

public byte[] GetBytes() {
return new byte[] {Byte0, Byte1, Byte2, Byte3};
}
}

You could then use it like this:
int myInt = 800;
IntBytes ib = new IntBytes(myInt);
byte[] bytes = ib.GetBytes();

I'm a C# newbie so that may not be the best code, but it does seem to work.
Another approach would be to create a MemoryStream around a byte array, then
use a BinaryWriter to write the integer to the stream (in effect, to the
array), like this:

byte[] bytes = new byte[4];
BinaryWriter writer = new BinaryWriter(new MemoryStream(bytes));
writer.Write(myInt);
writer.Close();

I hope that helps.
 
Hello

The .NET framework has the BitConverter class, that can convert any
primitive type to a byte array and vice versa.

int myInt = 800;
byte[] myByteArray = System.BitConverter.GetBytes(myInt);

Best regards,
Sherif
 
Back
Top