回首忆惘然
来自http://www.coderanch.com/t/236675/java-programmer-SCJP/certification/xff十六进制文字0xFF是一个等于int(255)。Java将int表示为32位。二进制看起来像这样:00000000 00000000 00000000 11111111当你对任何数字的这个值(255)进行一点点明智的AND时,它将屏蔽(生成ZERO)除了数字的最低8位(将是原样)。... 01100100 00000101 & ...00000000 11111111 = 00000000 00000101&是像%,但不是真的。为什么是0xff?这个((2的幂) - 1)。全部((2的幂) - 1)(例如7,255 ......)将表现得像%运算符。然后在二进制中,0是全零,255看起来像这样:00000000 00000000 00000000 11111111-1看起来像这样11111111 11111111 11111111 11111111当您执行0xFF的按位AND和0到255之间的任何值时,结果与值完全相同。如果任何高于255的值仍然结果将在0-255之内。但是,如果你这样做:-1 & 0xFF你得到00000000 00000000 00000000 11111111,它不等于-1的原始值(11111111十进制为255)。几点操作:(与问题无关)X >> 1 = X/2X << 1 = 2X检查任何特定位是否设置(1)或不设置(0) int thirdBitTobeChecked = 1 << 2 (...0000100) int onWhichThisHasTobeTested = 5 (.......101) int isBitSet = onWhichThisHasTobeTested & thirdBitTobeChecked; if(isBitSet > 0) { //Third Bit is set to 1 } 设置(1)特定位 int thirdBitTobeSet = 1 << 2 (...0000100) int onWhichThisHasTobeSet = 2 (.......010) onWhichThisHasTobeSet |= thirdBitTobeSet;重新设置(0)特定位int thirdBitTobeReSet = ~(1 << 2) ; //(...1111011)int onWhichThisHasTobeReSet = 6 ;//(.....000110)onWhichThisHasTobeReSet &= thirdBitTobeReSet;XOR请注意,如果执行两次XOR运算,将产生相同的值。byte toBeEncrypted = 0010 0110byte salt = 0100 1011byte encryptedVal = toBeEncrypted ^ salt == 0110 1101byte decryptedVal = encryptedVal ^ salt == 0010 0110 == toBeEncrypted :)XOR的另一个逻辑是if A (XOR) B == C (salt)then C (XOR) B == A C (XOR) A == B以上内容对于交换两个没有temp的变量非常有用,如下所示a = a ^ b; b = a ^ b; a = a ^ b;要么a ^= b ^= a ^= b;