We have a file which contains byte array in particular format like header and then followed by data. This file is generated by another java program and then we are reading that same file through another java program in the same format in which it was written.
The program which is making that file, populates lengthOfKey
as byte which is right as that's what we need as shown below.
for (Map.Entry<byte[], byte[]> entry : holder.entrySet()) {
byte typeKey = 0;
// getting the key length as byte (that's what we need to do)
byte lengthOfKey = (byte) entry.getKey().length;
byte[] actualKey = entry.getKey();
}
Now as byte
can only store maximum value as 127
, we are seeing for some of our record lengthOfKey
is coming as negative while we read the file as shown below:
Program which is reading the file:
byte keyType = dis.readByte();
// for some record this is coming as negative. For example -74
byte lengthOfKey = dis.readByte();
Now my question is : Is there any way I can find out what was the actual length of key because of that it got converted to -74
while writing it. I mean it should be greater than 127
and that's why it got converted to -74
but what was the actual value?
I think question would be how to convert negative byte value to either short or integer? I just wanted to verify to see what was the actual length of key because of that it got converted to negative value.
If the original length from
entry.getKey().length
is greater than255
, then the actual length information is lost. However, if the original length was between128
and255
, then it can be retrieved.The narrowing conversion of casting to
byte
keeps only the least significant 8 bits, but the 8th bit is now interpreted as-128
instead of128
.You can perform a bit-and operation with
0xFF
, which will retain all bits, but that implicitly widens the value back to anint
.Widening it to an
int
, with sign extension:Masking out the last 8 bits as an
int
:That will convert a negative
byte
back to a number between128
and255
.