Binary operations

1 minute read

Published:

Binary operations: & | ^ ~ rotate. Also, see reference1

Outline

  1. & AND operator (binary): when both = 1 => 1, else =>0
    • 1 & 1 = 1
    • 1 & 0 = 0
    • 0 & 1 = 0
    • 0 & 0 = 0
    • E.g. 1 0 1 0 & 1 1 0 0 = 1 0 0 0
  2. | OR operator (binary): when anyone = 1 => 1, else => 0
    • 1 | 1 = 1
    • 1 | 0 = 1
    • 0 | 1 = 1
    • 0 | 0 = 0
    • E.g. 1 0 1 0 | 1 1 0 0 = 1 1 1 0
  3. ^ XOR operator (binary): when different => 1, else => 0
    • 1 ^ 1 = 0
    • 1 ^ 0 = 1
    • 0 ^ 1 = 1
    • 0 ^ 0 = 0
    • E.g. 1 0 1 0 ^ 1 1 0 0 = 0 1 1 0
  4. ~ INVERSE operator (unary): 1 <=> 0
    • ~ 1 = 0
    • ~ 0 = 1
    • E.g. ~ 1 0 1 0 = 0 1 0 1
  5. >>>, >>, << SHIFT operator (unary)
    • 左移,低位通通补0
    • 右移
    • >>>: 无符号右移,忽略符号位,空位都以0补齐,高位补0
    • >>: 带符号移动,负数高位补1
      • 在计算机中是以数值是以该数的补码形式来表示
      • 正数:原码=反码=补码
      • 负数:计算机中负数的二进制是以负数的补码形式表示,反码=除符号位原码各位取反; 补码=反码+1
      • -107 => 1001 0101 >> 4 => 1111 1001
  6. ROTATE operator (unary), for int32 x, rotate n bits:
    • ROTATE left:
    • 将x左端的n位先移动到y的低n位中: x >> (32 - n);
    • 将x左移n位,其右面低位补0: x << n;
    • 进行按位或运算: (x >> (32 - n) | (x << n)); * ROTATE right:
    • 将x左端的n位先移动到y的低n位中: x << (32 - n);
    • 将x左移n位,其右面低位补0: x >> n;
    • 进行按位或运算: (x << (32 - n) | (x >> n));