开发者

understanding casting in this program

byte b = 5;
byte c = ~5;

this code if wr开发者_C百科itten in java gives error that cannot convert from int to byte. Also if i do

int c = ~5;

it gives -6 as result however i was expecting 3. What is the reason and how can i do a not to achieve 3 as result.


You're getting a negative number and not a positive because the byte primitive (as is short, int, long, etc.) is signed - so the most significant bit is flipped so it represents a negative number (using two's complement.) Invert all the bits on a positive number and it'll become negative (and vice versa.)

That said, you wouldn't get 3 anyway if it didn't - 5 is 101 in binary, which would produce 010 (2, not 3.)

As to why it has to be put in an int, from memory that's because the JLS states that all integer arithmetic has a return type of "at least" an int. It's the same reason as if you do byte b = 1+1 it still won't work, even though the result clearly fits into a byte.


I did not understand the error.

00000000 00000000 00000000 00000101 => 5
Applying the "~" operator:
11111111 11111111 11111111 11111010 => -6 in the complement 2.

What you cold do is, but not very good, just to understanding the problem: byte c = (byte) (0xFF) & ~5;

11111111 11111111 11111111 11111010 => -6 
Applying & 0xFF
00000000 00000000 00000000 11111111                                           
Results:
00000000 00000000 00000000 11111010 => 250 
So you cast to byte:
-------- -------- -------- 11111010 => -6

A simple: byte c = (byte) ~5; could solve your problem.


The code

byte b = 5;

is short hand for

byte b = (byte) 5;

it does the casting for you as its a constant expression the compiler can evaluate at compile time.

Also

byte b = ~5;

and even

final int i = 5;
byte b = ~i;

compile fine. Note: if i is not final, the second line does not compile.


Calculating a negative is the same as taking the complement and adding 1.

neg(a) = comp(a) + 1 or -a = ~a + 1 or ~a = -a - 1

so you would expect ~5 to be -5 - 1 = -6.


the bit representation of 5 is 00000101 then ~5 is 11111010

it's 2's complement is 00000110 which is bit representation of 6 and 11111010 is bit representation of -6.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜