I have an array of bytes (because unsigned byte isn’t an option) and need to take 4 of them into a 32 bit int. I’m using this:
byte rdbuf[] = new byte[fileLen+1];
int i = (rdbuf[i++]) | ((rdbuf[i++]<<8)&0xff00) | ((rdbuf[i++]<<16)&0xff0000) | ((rdbuf[i++]<<24)&0xff000000);
If i don’t do all the logical ands, it sign extends the bytes which is clearly not what I want.
In c this would be a no brainer. Is there a better way in Java?
You do not have to do this, you can use a
ByteBuffer:If you have many ints to read, the code becomes:
Javadoc here. Recommended for use in any situation where binary data has to be dealt with (whether you read or write such data). Can do little endian, big endian and even native ordering. (NOTE: big endian by default).
(edit: @PeterLawrey rightly mentions that this looks like little endian data, fixed code extract — also, see his answer for how to wrap the contents of a file directly into a
ByteBuffer)NOTES:
ByteOrderhas a static method called.nativeOrder(), which returns the byte order used by the underlying architecture;ByteBufferhas a builtin offset; the current offset can be queried using.position(), and modified using.position(int);.remaining()will return the number of bytes left to read from the current offset until the end;