I have a binary file with the byte 88 (which is 136 decimal).
I'm using Java's RandomAccessFile class and the "read" method to read this byte via a pre-defined buffer. I also tried "readUnsignedByte()" but get the same issue as below.
RandomAccessFile randomAccessFile = new RandomAccessFile(inputFile, "r");
byte[] headerBuffer = new byte[32];
randomAccessFile.read(headerBuffer);
The code above gives me -120 for 88, not 136.
I realize that the high-order bit or whatever is set, but I still need to be able to read the file and either get 88 or 136.
The issue is that this byte is the offset into the binary file where I can find the first record so a negative number won't work.
Would appreciate suggestions.
Thanks,
Just do b & 0xFF
to convert it to positive integer.
You can use the Byte.toUnsignedInt
method to convert a byte
into an int
in an "unsigned" way.
jshell> byte b = (byte) 0x88;
b ==> -120
jshell> Byte.toUnsignedInt(b);
$57 ==> 136
The operation is the same as b & 0xff
but doesn't invoke magic numbers or knowledge about bitwise operators.
The method read(byte[])
you use for reading multiple bytes at-once actually reads a signed byte as in readByte()
. Thus you're right, the first bit represents the sign and will thus be interpreted by Java potentially leading to negative number.
Benefit of random-access is to jump to the position/offset in file using seek(long)
. So, if you know the exact position of that record-pointer byte, you can jump there and proceed reading the desired byte as unsigned using readUnsignedByte()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.