Are the &, |, ^ bitwise operators or logical operators?

前端 未结 4 1852
暖寄归人
暖寄归人 2020-12-06 21:40

Firstly I learnt that &, |, ^ are the bitwise operators, and now somebody mentioned them as logical operators with &&

4条回答
  •  青春惊慌失措
    2020-12-06 21:48

    The Java type byte is signed which might be a problem for the bitwise operators. When negative bytes are extended to int or long, the sign bit is copied to all higher bits to keep the interpreted value. For example:

    byte b1=(byte)0xFB; // that is -5
    byte b2=2;
    int i = b1 | b2<<8;
    System.out.println((int)b1); // This prints -5
    System.out.println(i);       // This prints -5
    

    Reason: (int)b1 is internally 0xFFFB and b2<<8 is 0x0200 so i will be 0xFFFB

    Solution:

    int i = (b1 & 0xFF) | (b2<<8 & 0xFF00);
    System.out.println(i); // This prints 763 which is 0x2FB
    

提交回复
热议问题