How do I break an integer into its component bytes?

Raymond Chen

Warning: .NET content ahead. For some reason, this gets asked a lot.

To break an integer into its component bytes, you can use the BitConverter.GetBytes method:

int i = 123456;
byte[] bytes = BitConverter.GetBytes(i);

After this code fragment, the byte array contains { 0x40, 0xE2, 0x01, 0x00 }.

Update 11am: The endian-ness of the result is determined by the BitConverter.IsLittleEndian property. Thanks to reader Sean McVey for pointing this out.


Discussion is closed.

Feedback usabilla icon