Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c#: Convert an int into the smallest byte array it will fit into

Tags:

c#

bytearray

I would like an elegant, efficient means of taking any unsigned integer and converting it into the smallest byte array it will fit into. For example:

250 = byte[1]
2000 = byte[2]
80000 = byte[3]

so that I can write:

var foo = getBytes(bar);

and foo will be of different lengths depending on the value of bar. How would I do that?

like image 925
Jeremy Holovacs Avatar asked Nov 07 '11 14:11

Jeremy Holovacs


1 Answers

You can do it like this, as an extension method:

public static byte[] ToByteArray(this int value) {
     var bytes = Enumerable
                     .Range(0, sizeof(int))
                     .Select(index => index * 8)
                     .Select(shift => (byte)((value >> shift) & 0x000000ff))
                     .Reverse()
                     .SkipWhile(b => b == 0x00)
                     .ToArray();
     return bytes;
}

Then:

int j = 2000;
var bytes = j.ToByteArray();
Console.WriteLine(bytes.Length);
for(int index = 0; index < bytes.Length; index++) {
    Console.WriteLine("{0:x}", bytes[index]);
}

Gives:

2
0x07
0xd0

And replacing j = 2000 by j = 80000 in the above gives

3
0x01
0x38
0x80

And replacing j = 2000 by j = 250 in the above gives

1
0xfa
like image 198
jason Avatar answered Sep 21 '22 08:09

jason