Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Int to byte array

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?

like image 585
Brady Moritz Avatar asked Nov 14 '10 07:11

Brady Moritz


People also ask

Can we convert int to byte in Java?

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).

What is byte array?

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.


1 Answers

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.

like image 66
Marc Gravell Avatar answered Sep 22 '22 17:09

Marc Gravell