The Answer to Life, the Universe, and Everything

Tuesday, September 12, 2006

int <=> byte[]

In some occation such as the low level processing in the Java programming, you might need to convert the "int" data into "byte array" and the opposite case as well.

Here is the sample code ( in my case for CLDC1.0 or 1.1 programming).

Converting the int data type into byte array.

/**
* In order to conver the int data type into byte array
* @param value the int value you want to convert
* @return byte array data
*/
public static byte[] getIntBytes(int value) {
byte[] b = new byte[4];
b[0] = (byte) ((value >>> 24) & 0x000000FF);
b[1] = (byte) ((value >>> 16) & 0x000000FF);
b[2] = (byte) ((value >>> 8) & 0x000000FF);
b[3] = (byte) (value & 0x000000FF);
return b;
}


Converting the byte array into int data type

/**
* In order to convert the byte array into int data type
* @param value the byte array you want to convert
* @return int data
*/
public static int getInt(byte value[]) {
int ret = 0;
ByteArrayInputStream bais = null;
try {
bais = new ByteArrayInputStream(value);
ret = new DataInputStream(bais).readInt();
bais.close();
bais = null;
} catch (Throwable t) {
t.printStackTrace();
} finally {
if (bais != null) {

try {
bais.close();
bais = null;
} catch (Throwable t) {
}
}
}
return ret;

}

No comments: