Skip to main content

Help on getting at the bytes of an int

1 reply [Last post]
frank_houser
Offline
Joined: 2008-09-24
Points: 0

I'd like to do something like:

int myInt;
byte[] i32 = toBytes (myInt, littleEndian);

and the reverse:

byte[] i32 = ...
int myInt = toInt (i32, littleEndian);

Is there any way to do it simply in Java. The only way I can figure out right now involves IO streams, which seems like a lot of typing (and computation) for just this simple thing.

thank you!!

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
frank_houser
Offline
Joined: 2008-09-24
Points: 0

Sometimes you miss the obvious, so I guess I can do something like this:

int i = 1234;
byte[] lendian = new byte[4];
lendian[0] = (byte)(i >> 24);
lendian[1] = (byte)(i >> 16);
lendian[2] = (byte)(i >> 8);
lendian[3] = (byte)(i >> 0);

More efficient than using streams, since JVM is always big endian so it'll work for Java. If I don't find anything else, this will have to do.
*noticed its is big endian, but you get the picture. I'm still looking for a better way.

Message was edited by: frank_houser