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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With