Reputation: 20557
So I am sending some stuff over bluetooth, for this I am using byte arrays, one of the byte arrays I am using I need to change one of the values before I send it, using this...
private void sendIntensity(int I){
intensity[3] = (byte) i;
sendIntensity();
}
The original byte array is made up like this:
private byte[] intensity = new byte[]{58,0,42,0,10,13}
I am getting the intensity from an edit text, getting the text and using regex to find the intensity they want to use, I use
int option = Integer.parseInt(text);
To do that. Basically, any number under 128 works perfectly, I can see this because I log the values in the array, setting it to 127 will log 58, 0, 42, 127, 10, 13
but when I do 128 or over I get a weird set of data when I log it.
The max number I will be putting in there is 255.
When I log what is in the array when use intensity[3] = (byte) 128;
I get back 50, 0, 42, -17, -66, -128, 10, 13
When I log what happens when I use 129 I get back 50, 0, 42, -17, -66, -127, 10, 13
What is happening? Why am I not just getting back 50, 0, 42, 128, 10, 13
like I should be?
Upvotes: 0
Views: 965
Reputation: 85779
That's because byte
range is [-128, 127]
, if you try to set a value larger than 127
in a byte
, it will do a round trip to -128
, -127
and so on.
From the SCJP 6 book:
byte a = (byte) 128;
(...) what's the result? When you narrow a primitive, Java simply truncates the higher-order bits that won't fit. In other words, it loses all the bits to the left of the bits you're narrowing to.
More info:
Upvotes: 2
Reputation: 10943
It is simply due to byte characteristic in java upto 128 from -128 thats all
Upvotes: 0