Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How convert integer to two bytes array

807580Feb 18 2010 — edited Feb 22 2010
Hi. I'm developing the LZW compression algorithm and I trying to write the minimum bytes in the output file so as to save more space.

I have the following code which converts an integer to a bytes array of size 4.
public static final byte[] intToByteArray(int value) {

        return new byte[] {
                (byte)(value >>> 24),
                (byte)(value >>> 16),
                (byte)(value >>> 8),
                (byte)value};
} 
I need to parametrize it so as to return a variable-length array of bytes (for doing the benchmark), something like:
public static final byte[] intToByteArray(int value, int size) 
The same for the opposite code:
public static final int byteArrayToInt(byte [] b) {

        return (b[0] << 24) 
                + ((b[1] & 0xFF) << 16)
                + ((b[2] & 0xFF) << 8)
                + (b[3] & 0xFF);
} 
public static final int byteArrayToInt(byte [] b, int size)
Is possible what I am asking? Can someone explain me how this methods work and how can I parametrized them?

Thanks!

Edited by: Akcents on Feb 18, 2010 11:14 PM
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 22 2010
Added on Feb 18 2010
50 comments
1,163 views