我看一个有名的开源组件,用到byte--->char代码是这样的:
c[i] = (char) (b[i] & 0xff)  (b[i]为byte型,c[i]为char型)
觉得与一下0xff没什么用。直接c[i] = (char)b[i]有何异?

解决方案 »

  1.   

    I don't know the difference...Maybe they are the same...
      

  2.   

    因为byte的取值范围是 -128~127,而Char是0~65535所以需要& 0xFF 使得byte原来的负值变成正的
      

  3.   

    But it changes the byte value, doesn't it?
      

  4.   

    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:
      

  5.   

    与 0xff 做 & 运算会将 byte 值变成 int 类型的值,也将 -128~0 间的负值都转成正值了。
      

  6.   

    char c = (char)-1 & 0xFF;
    char d = (char)-1;
    System.out.println((int)c);
    System.out.println((int)d);
    这样输出是 255
    65535
    上面代码就是为了避免错误
      

  7.   

    补充一下:
    1)。位运算符只针对4byte的int型
    2)。-2的byte类型 16进制表示为 FE(2取反加1)
    3)。-2 & 0xFF运算: 实际-2带符合bit-wise成int,即FE会变成FFFFFFFE(2取反加1), 接着
      0xFFFFFFFE & 0x000000FF = 0x 000000FE; 如果不&,就是FFFFFFFE。
      

  8.   

    1) 位运算不限制为int, long也行的。
    2) 
    3) 负数进行&操作时需要转成补码,-2 的补码是0xFFFFFFFE
      

  9.   

    這個是unsigned shifting用的辦法..
    java中的數值是int,所以0xFF是int,而byte是有符號數,int亦然,直接由byte升為int,符號自動擴展,而進行了& 0xFF後,就把符號問題忽略掉了,將byte以純0/1地引用其內容,所以要0xFF,不是多餘的,你用一些Stream讀取文件的byte就知道了,我昨天搞了一天,就不明白為什麼讀出來的數某些byte會在移位後錯誤的,就是因為這個原因.
      

  10.   

    這個是unsigned shifting用的辦法..
    java中的數值是int,所以0xFF是int,而byte是有符號數,int亦然,直接由byte升為int,符號自動擴展,而進行了& 0xFF後,就把符號問題忽略掉了,將byte以純0/1地引用其內容,所以要0xFF,不是多餘的,你用一些Stream讀取文件的byte就知道了,我昨天搞了一天,就不明白為什麼讀出來的數某些byte會在移位後錯誤的,就是因為這個原因.
      

  11.   

    Mark~源码的学习看样子是必须的啦