《Java puzzlers》里关于 sign extension 的示例
PHP中文网
PHP中文网 2017-04-18 09:45:37
0
3
527

原文:
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

PHP中文网
PHP中文网

认证0级讲师

reply all(3)
黄舟

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template