You can do it as follows:
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 when replacing j = 2000 with j = 80000 in the above example
3 0x01 0x38 0x80
And when replacing j = 2000 with j = 250 in the above example
1 0xfa
jason source share