1

I am having a hard time trying to perform what should be a simple conversion from an integer to a byte array.

I feel this must be simple, even trivial, but cannot get it (so if anyone know the right "name" for this operation, please tell me). Also, I couldn't find a better question title, but I feel it's a bit vague (feel free to edit).

What I want:

byte[] result = MagicConverter.Convert(336);
// now result should be {0, 0, 1, 80}

The result of converting 336 should be 1, 80 because that is the decomposition in base 256, that is, 1*256 + 80 = 336.

My codebase contain a lot of bitshifting stuff to perform similar tasks, but I think I'm not quite inderstanding this bitshifting thing yet.

4
  • 2
    1*256+80 = 336, not 366 Commented Feb 5, 2015 at 18:49
  • 1
    A side note, if you're planning to use this for communicating byte arrays with other applications, you may need to research Endianness. Different platforms will store the bytes for an integer in different orders and that order can matter when inter-operating. Commented Feb 5, 2015 at 18:57
  • @Matt you are right, it was a typo! Commented Feb 5, 2015 at 18:58
  • @DanBryant you are right! Most probably my device uses BigEndian, 'cause I need to reverse the order according to the accepted answer. Commented Feb 5, 2015 at 19:01

3 Answers 3

5
BitConverter.GetBytes(366); 

Should do the trick.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice! I felt it should be "obvious" :) One note though: in order to get the order I need, I have to do: bytes = BitConverter.GetBytes(366); var reversed = bytes.Reverse().ToArray(); return reversed;
1

What you're looking for is BitConverter.GetBytes():

byte[] result = BitConverter.GetBytes(366);

Comments

0

You can use the BitConverter.GetBytes() function to do this.

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.