Skip to content

Instantly share code, notes, and snippets.

@pepplejoshua
Last active January 1, 2024 06:41
Show Gist options
  • Save pepplejoshua/853145d5c89c200894e3a00cd662508a to your computer and use it in GitHub Desktop.
Save pepplejoshua/853145d5c89c200894e3a00cd662508a to your computer and use it in GitHub Desktop.
Left shift and right shift operators (<< and >>)

Implementing LC-3 in zig and it seems like a good time to take some notes on how they work (or how to intuitively tell what they are doing.

Left shift

From my understanding, the form a << b can get turned into a * (2 ^ b) mathematically. So 1 << 2 becomes 1 * (2 ^ 2), which is 4.
From a more natural view, taking 1 to binary with 5 bits gives 00001. If we say shift it left 2 times, it will become 00100, which is 4. Very nice.

Right shift

The form a >> b can get turned into quotient(a / (2 ^ b)) mathematically. So 14 >> 2 becomes quotient(14 / (2 ^ 2)), which is 3. 14 / 4 is 3.5, the quotient of which is 3.
From the alternate view, taking 14 to binary with 5 bits gives 01110. If we shift it right twice, it will become 00011, which is 3. This way seems simpler to me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment