tags:

views:

171

answers:

4

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

+5  A: 

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.

Marc Gravell
This is my solution. Much must faster than BitConverter.
Joshua
@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.
Dan Bryant
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.
Joshua
@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.
Dan Bryant
Try it on mono, get burned. Not that most people care.
Joshua
@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?)
Marc Gravell
+4  A: 

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

Reed Copsey
+2  A: 

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);
Larsenal
+1  A: 

Is it an int16?

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

This will only have two bytes in it.

Abe Miessler