I have a byte array:
byte[] b = [108, 108, -17, 65] // Arrays.toString(b)
and I want to turn negatives into negatives +256, like: -17 + 256 = 239
so that I have:
b = [108, 108, 239, 65]
I tried:
ByteBuffer buffer = ByteBuffer.wrap(b);
for(int i = 0; i < 4; i++){
if (b[i] < 0){
int n = (b[i] + 256);
byte b1 = (byte) (b[i] + 256);
buffer.position(i);
buffer.put(i, (byte) (n & 0xFF));
}
}
but nothing changes.
I would be very thankful for any advices
You can’t represent anything over 127 as a positive valued byte. So you would have to have an array of ints
to show
the value like you want. I use the word show
because it is important to realize that this is just a representation of the actual value for use by humans. It has no bearing on the intrinsic nature of the value.
byte b = 239;
System.out.println(b);
Prints
-17
I suspect you would want the unsigned value which can be printed like so.
byte b = -17;
System.out.println(Byte.toUnsignedInt(b));
Prints
239