0

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.

3
  • 3
    You can't encode all the possible values of an int in C# into just 3 bytes, so you're going to have to lose 8 bits either way, dropping "the last byte" seems every bit as good as an alternative, or did your question for a "better way" ask if there's a way to avoid dropping bits at all? Please clarify how you would judge if an alternate solution is better or worse than just "dropping the last byte". Commented Oct 6, 2016 at 10:02
  • 4
    Better way of doing it than what? I don't see any code nor I see an explanation of what you are trying to achieve so it's quite impossible to tell you what is the best way to implement that. Commented Oct 6, 2016 at 10:02
  • This is effectively a follow-up question to their earlier one Commented Oct 6, 2016 at 10:04

2 Answers 2

2

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),
  };
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.