How do I convert an int to two bytes in C#?

16,235

Solution 1

Assuming you just want the low bytes:

byte b0 = (byte)i,
     b1 = (byte)(i>>8);

However, since 'int' is 'Int32' that leaves 2 more bytes uncaptured.

Solution 2

You can use BitConverter.GetBytes to get the bytes comprising an Int32. There will be 4 bytes in the result, however, not 2.

Solution 3

Another way to do it, although not as slick as other methods:

Int32 i = 38633;
byte b0 = (byte)(i % 256);
byte b1 = (byte)(i / 256);

Solution 4

Is it an int16?

Int16 i = 7;
byte[] ba = BitConverter.GetBytes(i);

This will only have two bytes in it.

Share:
16,235
xarzu
Author by

xarzu

Why Would I Use My Real Name When "Xarzu" Is so Cool? (I am not really 90 years old either) http://s3.envato.com/files/190523.jpg

Updated on July 17, 2022

Comments

  • xarzu
    xarzu almost 2 years

    How do I convert an int to two bytes in C#?

  • vpalmu
    vpalmu over 13 years
    This is my solution. Much must faster than BitConverter.
  • Dan Bryant
    Dan Bryant over 13 years
    @Joshua, I did a quick bench-mark (Release build, 50000000 iterations, Stopwatch and full test repeated twice to remove various artifacts) and the difference between creating an array and using the bit-masking vs. calling BitConverter is approximately 1ns per call on my machine. If you remove the array creation (just get the two bytes), the difference is about 14ns.
  • vpalmu
    vpalmu over 13 years
    I don't doubt your benchmarks. BitConverter is slow in comparison because it has to allocate arrays. If I can pre-detect my array size for thousands of integers I can save a nontrivial amount of time.
  • Dan Bryant
    Dan Bryant over 13 years
    @Joshua, non-trivial is, of course, relative. At a 14ns difference, you'll have to execute 1 million iterations to observe a 14ms delay from the extra array allocation. Memory allocation for small temporary objects by the CLR is actually quite cheap. This is a consequence of the garbage collector design, which compacts the heap during collection, allowing allocation without requiring handling of fragmentation.
  • vpalmu
    vpalmu over 13 years
    Try it on mono, get burned. Not that most people care.
  • Marc Gravell
    Marc Gravell over 13 years
    @Joshua - it isn't Mono that is the issue - it is different-endianness. The shift approach side-steps this completely (I assume the Mono comment was aimed at BitConverter, not shift?)
  • Ky -
    Ky - almost 10 years
    Can we note that this is pretty language-independent?
  • user964829
    user964829 over 3 years
    can you please explain how to get back the integer from 2 bytes using this solution