Skip to content

Instantly share code, notes, and snippets.

@raphaelrk
Last active February 23, 2016 20:58
Show Gist options
  • Save raphaelrk/2d46905e7643a5f8a74f to your computer and use it in GitHub Desktop.
Save raphaelrk/2d46905e7643a5f8a74f to your computer and use it in GitHub Desktop.
Let's do a speedy run-down on bitwise operators
First, know or recall that we can write the number 12 in three different ways
int twelve_dec = 12;
int twelve_hex = 0xC;
int twelve_bin = 0b1100;
bitwise operators operate bit-by-bit
NOT (complement) ~00000001100 = 11111110011
OR 0b1100 | 0b1010 = 0b1110
AND 0b1100 & 0b1010 = 0b1000
XOR ^ 0b1100 ^ 0b1010 = 0b0110
shift left << 0b0011 << 2 = 0b1100
shift right >> 0b1100 >> 1 = 0b0110
don't forget these mostly apply to booleans, with
false as 0
true as 1
in an if statement anything that isn't 0 is true is true
use ! instead of ~
a ? b : c;
Applications:
cryptography
m = (m ^ k) ^ k
swap without a temp
val1, val2
val1 = val1 ^ val2
val2 = val1 ^ val2
val1 = val2 ^ val1
upper and lowercasing
chr & 0xdf
RGB
color & (0xff)
times and divide two
>> n
<< n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment