原文:
If you are converting from a byte value b to a char and you don’t want sign
extension, you must use a bit mask to suppress it. This is a common idiom, so no
comment is necessary:
char c = (char) (b & 0xff);
没有get到 sign extension的含义!以及为什么这么做就没有sign extension
First of all, char is 16 bits and byte is 8 bits. Byte has a negative form but char does not. If you do a shift directly, the negative byte will be directly extended according to the first sign bit 1 and become 111111111xxxxxx. However, this problem will not occur when doing bitwise AND
I understand it is the symbol bit
When performing bit operations, except long type, other types will be automatically converted to int type. don't want sign extension means that this does not use the first matching bit of byte to convert to char. There is no unsigned type in Java, and the char range is - 2^16-2^16-1, char is two bytes, for example, byte b=-1, and the first bit is used as the sign bit char c=(char)b, then the c binary bit (complement code) is expressed as 1111 1111 1111 1111 is -1, and two bytes represent -1; if the first bit is not used as the sign bit, such as char c=(char)(b&0xff), then the binary bit (complement code) of c is expressed as 0000 0000 1111 1111, which is 255, The two-character byte represents 255.