int -> byte[]
Hi.
I need to convert a single <b>int</b> to the <b>byte</b> array in the following way:
int i = 4096; //I want to convert this value to the array of 4 bytes, like this:
byte[] b = {0B, 0B, 16B, 255B}; // it's like: 00 00 0F FF
Is there any embedded java method which can do this? I cannot find it...
Many thanks
Miso
[385 byte] By [
mvpa] at [2007-10-2 4:04:55]

No, there is no embedded method, but there are some ways how to do that:
1. The most obvious way is using shift and mask operators to extract the four bytes. This might also be the fastest way.
2. A more complex, but nevertheless interesting way might be
- allocate a java.nio.ByteBuffer
- set the intended ByteOrder
- write the int to the ByteBuffer
- rewind the ByteBuffer
- read the four bytes into a byte[]
This also works. Seems like a lot of work for a simple task. If you just wanted the guts of algorithm, look at DataOutput.writeInt(...).
/**
* Converts an integer number to a byte[] of length 4.
*
* @return
* @throws IOException
*/
public static byte[] convertIntToBytes(int intVal)
throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeInt(intVal);
byte[] intAsBytes = baos.toByteArray();
dos.close();
return intAsBytes;
}
fitz