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