Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Convert int to Byte Array of 4 Bytes? [duplicate]

Tags:

java

byte

buffer

Possible Duplicate:
Convert integer into byte array (Java)

I need to store the length of a buffer, in a byte array 4 bytes large.

Pseudo code:

private byte[] convertLengthToByte(byte[] myBuffer) {     int length = myBuffer.length;      byte[] byteLength = new byte[4];      //here is where I need to convert the int length to a byte array     byteLength = length.toByteArray;      return byteLength; } 

What would be the best way of accomplishing this? Keeping in mind I must convert that byte array back to an integer later.

like image 780
Petey B Avatar asked Jun 16 '11 16:06

Petey B


People also ask

How do you convert int to Bytearray?

The Ints class also has a toByteArray() method that can be used to convert an int value to a byte array: byte[] bytes = Ints. toByteArray(value);

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

Is int always 4 bytes in Java?

On 16-bit systems (like in arduino), int takes up 2 bytes while on 32-bit systems, int takes 4 bytes since 32-bit=4bytes but even on 64-bit systems, int occupies 4 bytes.


1 Answers

You can convert yourInt to bytes by using a ByteBuffer like this:

return ByteBuffer.allocate(4).putInt(yourInt).array(); 

Beware that you might have to think about the byte order when doing so.

like image 182
Waldheinz Avatar answered Sep 22 '22 19:09

Waldheinz