Reputation: 19474
//Ok makes sense
Byte b = (byte)207;
System.out.println(b); //value = 207
//ok doesn't make sense
Integer x = Integer.parseInt("11001111", 2); //207
Byte sens = (byte)x.intValue(); //207
System.out.println(sens); //Value = -49
System.out.println(sens.intValue()); //Value = -49
Whats going on here?
How do I declare/represent an 8 bit byte with a value higher than 127 then
Upvotes: 3
Views: 9685
Reputation: 405
255 + the negative byteValue + 1 returns your number with the counter operation. Still recommend storage in a int.
If you like it bitwise, better put a numeric ring around it.
Upvotes: 0
Reputation: 1
The reason why it can't go over 127 positive, but it can go 128 negative, is that the first 1 out of the 8 digits in a byte represents if it is a negative number or positive:
1 = negative
0 = positive
and since you can use "1111 1111" for negative numbers, you can get -127.
Upvotes: 0
Reputation: 11443
Since Java's Byte is signed you can't represent value larger than 127 in byte.
In Your example:
Byte b = (byte)207;
System.out.println(b); //value = 207
There is an error. Output of println is -49.
Byte b = (byte)207;
System.out.println(b); //value = -49
Which means that both cases are identical.
Upvotes: 1
Reputation: 3322
bytes in Java are signed, so they go from -128 to 127. Casting an int like that will pick up the high bit at 1 (indicating a negative number in two's complement signed numbers) and convert it to the negative number -49.
From there, when you convert it back to an integer with sens.intValue()
, it picks up the new negative value and returns it, so you still get -49.
You will need to store bytes larger than 128 in an int
datatype, unfortunately.
Upvotes: 9