Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

java - Promotion of byte to int or long

If I have an byte value 00101011 and I want to represent it as int value I have: 00000000000000000000000000101011, what seems to be clear for me. Bu I have problem with byte value 11010100 which as int is represented by 11111111111111111111111111010100. I don't know where it came from. Can someone explain me the idea of extension byte value to int?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The byte value 11010100 represents a negative number (-44), because the most significant bit is set. When this undergoes primitive widening conversion, it must still represent the same negative value in the two's complement representation. This done using sign extension. That means that all new bits are the same as the original sign bit.

                           11010100 => -44
11111111 11111111 11111111 11010100 => -44

If this did not occur, then the sign bit would no longer be a sign bit, and it would be interpreted "normally", and the value would no longer be the same.

00000000 00000000 00000000 11010100 => 212

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...