I thought .net had some kind of easy conversion method to use for converting an int into a byte array? I did a quick search and all solutions are bit masking/shifting one byte at a time, like "the good ol days". Is there not a ToByteArray() method somewhere?
The byteValue() method of Integer class of java. lang package converts the given Integer into a byte after a narrowing primitive conversion and returns it (value of integer object as a byte).
A byte array is simply a collection of bytes. The bytearray() method returns a bytearray object, which is an array of the specified bytes. The bytearray class is a mutable array of numbers ranging from 0 to 256.
Update for 2020 - BinaryPrimitives
should now be preferred over BitConverter
. It provides endian-specific APIs, and is less allocatey.
byte[] bytes = BitConverter.GetBytes(i);
although note also that you might want to check BitConverter.IsLittleEndian
to see which way around that is going to appear!
Note that if you are doing this repeatedly you might want to avoid all those short-lived array allocations by writing it yourself via either shift operations (>>
/ <<
), or by using unsafe
code. Shift operations also have the advantage that they aren't affected by your platform's endianness; you always get the bytes in the order you expect them.
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