当前位置: 代码迷 >> J2SE >> byte转char,为什么要& 0xff,该如何解决
  详细解决方案

byte转char,为什么要& 0xff,该如何解决

热度:56   发布时间:2016-04-24 12:20:22.0
byte转char,为什么要& 0xff
我看一个有名的开源组件,用到byte--->char代码是这样的:
c[i] = (char) (b[i] & 0xff) (b[i]为byte型,c[i]为char型)
觉得与一下0xff没什么用。直接c[i] = (char)b[i]有何异?

------解决方案--------------------
避免java隐含的符号扩展吧
------解决方案--------------------
因为byte的取值范围是 -128~127,而Char是0~65535

所以需要& 0xFF 使得byte原来的负值变成正的
------解决方案--------------------
Java code
0xFF is hexidecimal, you can Wikipedia that part. FF is a representation of 00000000 00000000 00000000 11111111(a 32-bit integer)& means bit-wise "and", and so when you use it on two ints, each pair of bits from those two ints is and-ed and the result is placed in the resultant int:Example (showing 16 bits only)0101 1100 1010 1100&0000 0000 1111 1111-----------------=0000 0000 1010 1100So as you can see, 0xFF is often used to to isolate a byte in an integer, by truncating the integer to one byte's worth of 1's.For more information, see this WP article:
------解决方案--------------------
与 0xff 做 & 运算会将 byte 值变成 int 类型的值,也将 -128~0 间的负值都转成正值了。
------解决方案--------------------
Java code
char c = (char)-1 & 0xFF;char d = (char)-1;System.out.println((int)c);System.out.println((int)d);
------解决方案--------------------
1) 位运算不限制为int, long也行的。
2) 
3) 负数进行&操作时需要转成补码,-2 的补码是0xFFFFFFFE
  相关解决方案