문제

1) Why is the following assignment not allowed:

byte b = 0b11111111; // 8 bits or 1 byte

but this assignment is allowed:

int i = 0b11111111111111111111111111111111; //32 bits or 4 bytes

Both types are signed, and I would expect b and i were -1.

2) Why doesn't the Integer MIN_VALUE have a sign?

public static final int   MIN_VALUE = 0x80000000;

but the Byte MIN_VALUE does have a sign?

public static final byte   MIN_VALUE = -128;
도움이 되었습니까?

해결책 2

All integer literals have type int (unless suffixed by an L or l). Thus, in the first case, you're storing an int into a byte. A narrowing conversion like this is not allowed without a cast, except that if the right side is a constant, it's allowed if the value is in range, which is -128 to 127. 0b11111111 is 255, though, which is not in range.

As for why int i = 0b11111111111111111111111111111111 is allowed: it's pretty much "because the JLS says so". In fact, that specific example appears in JLS 3.10.1. There's a rule that decimal literals of type int cannot exceed 214743647 (except in the specific case -2147483648), but there's no rule about binary literals except that they have to fit into 32 bits.

As I mentioned in a comment, the second question is really a question about the style preference of the programmers who wrote the code, and it's impossible to answer.

다른 팁

Question 1)

This is because 0b11111111 is an int literal, whose value is 255. This value doesn't fit into a byte. See http://docs.oracle.com/javase/7/docs/technotes/guides/language/binary-literals.html for more details on this.

Question 2)

When we write binary or hexadecimal literals, we never put a sign. The literal 0x80000000 is actually a negative value, even though we don't write it as such.

There's no really good reason why the makers of the JDK chose to use a decimal literal for -128 but a hexadecimal literal for 0x80000000; except that in each case, it's probably a whole lot clearer that way what is intended.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top