Sunday, January 27, 2008

Convert Integer to Byte in Java

I have been working on the Huffman Encode/Decode and this has been the most annoying part of the Encoder piece of the program----Converting an integer into a 3-byte or 4-byte representation.


private static int[] generateByte(int integer, int byteLength) {
int[] byteStr = null;
if (byteLength==4){
byteStr=new int[4];
byteStr[0]=(byte)((integer & 0xff000000)>>>24);
byteStr[1]=(byte)((integer & 0x00ff0000)>>>16);
byteStr[2]=(byte)((integer & 0x0000ff00)>>>8);
byteStr[3]=(byte)((integer & 0x000000ff));
}

if (byteLength==3){
byteStr=new int[3];
byteStr[0]=(byte)((integer & 0x00ff0000)>>>16);
byteStr[1]=(byte)((integer & 0x0000ff00)>>>8);
byteStr[2]=(byte)((integer & 0x000000ff));
}
return byteStr;
}

Reference:
1. Java Forum Post: Convert integer to 4 byte[ ] array and back to integer value
2. Java Quick Reference: Operators and Assignments - Binary/Octal/Hex and Decimal Number Systems

1 comment:

Anonymous said...

Integer/= integer