Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16310

How to convert an int to a byte array of size 3?

I need to convert an int to a byte array of size 3. This means dropping the last byte, for example:

var temp = BitConverter.GetBytes(myNum).Take(3).ToArray());

However, is there a better way to do is? Maybe by creating a custom struct?

EDIT

For this requirement I have a predefined max value of 16777215 for this new data type.

Upvotes: 0

Views: 323

Answers (2)

starlight54
starlight54

Reputation: 1091

Sounds like you want to create a new struct that represents a 3 byte unsigned integer (based solely on the max value quoted).

Using your original method is very prone to failure, firstly, Take(3) is dependent on whether the system you're running on is big-endian or little-endian, secondly, it doesn't take into account what happens when you get passed a negative int which your new struct can't handle.

You will need to write the conversions yourself, I would take in the int as given, check if it's negative, check if it's bigger than 16777215, if it passes those checks then it's between 0 and 16777215 and you can store it in your new struct, simply execute a Where(b => b != 0) instead of Take(3) to get around the endian-ness problem. Obviously take into account the 0 case where all bytes = 0.

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186728

Something like this (no Linq, just getting bytes)

  int value = 123;

  byte[] result = new byte[] {
    (byte) (value & 0xFF),
    (byte) ((value >> 8) & 0xFF),
    (byte) ((value >> 16) & 0xFF),
  };

Upvotes: 2

Related Questions