Skip to content

Instantly share code, notes, and snippets.

@Unam3dd
Created June 22, 2022 11:01
Show Gist options
  • Save Unam3dd/bca15aca5d98587c992eaeda9c1c6bd0 to your computer and use it in GitHub Desktop.
Save Unam3dd/bca15aca5d98587c992eaeda9c1c6bd0 to your computer and use it in GitHub Desktop.
bitwise operators tricks
atoi example
https://fr.wikipedia.org/wiki/Table_de_v%C3%A9rit%C3%A9
Bitwise tricks
All these tricks are also used in cryptography and obfuscation methods.
AND
Take bits in bytes
0xDEADBEEF & 0xFFFF0000 = 0xDEAD0000
0xDEADBEEF & 0x0000FFFF = 0xBEEF
char to int digits
51('3') in ascii in hex is 0x33 & 0xF = we get 3 in integer
Check is odd or even
0x2 & 0x1 == 0 is even
NOT
Increment by one
-~n = -~1 = 2
Decrement by one
~-n = ~-1 = 0
XOR
Xor is very used in cryptography systems
set zero variable or anything
a = 42
a ^= a // a is now at 0
Swap lowercase & Uppercase
a = 'a'
a ^= 32 // a is now Uppercase
a = 'A'
a ^= 32 // A is now lowercase
a = 'A'
a |= 32 // a is now lowercase
Check if two integer have same sign
-2 ^ -2 >= 0 = yes
3 ^ 3 >= 0 = yes
3 ^ -3 >= 0 = No
Swap two elements
Xor swap algorithm
https://en.wikipedia.org/wiki/XOR_swap_algorithm
a = 2
b = 4
a ^= b
b ^= a
a ^= b
a is now 4
and b is now 2
Compare two elements
a = 4
b = 4
a ^ b == 0 // then is equal
Add two binary numbers
4 | 1 = 5
2 | 1 = 3
2 | 2 = 3
Bitshift
Concat two bytes
(0xDE << 8 | 0xAD)
Swap bits
Swap one byte (replace two nibble bytes)
((42 >> 4) | (42 << 4)) & 0xFF
Swap word
((0xBEEF >> 8) | (0xBEEF << 8)) & 0xFFFF
Swap dword
((0xDEADBEEF >> 16) | (0xDEADBEEF << 16)) & 0xFFFFFFFF
Swap qword
((0xDEADBEEFBADCAFFE >> 32) | (0xDEADBEEFBADCAFFE << 32)) & 0xFFFFFFFFFFFFFFFF
Increase power
1 << 1 = 2
1 << 2 = 4
Decrease power
4 >> 1 = 2
4 >> 2 = 1
Mul by 10
(2 << 1) + (2 << 3) = 20
Encode In Hex
97 = 0x61
97 >> 4 = 6
97 & 0xF = 1
97 / 16 = 6
97 % 16 = 1
https://fr.wikipedia.org/wiki/Alg%C3%A8bre_de_Boole_(logique)
Get max of two integer
a = 5
b = 12
b & ((a - b) >> 31) | a & (~(a - b) >> 31)
Get min of two integer
a = 5
b = 12
a & ((a-b) >> 31) | b & (~(a-b) >> 31);
Check if number is a power of two
num > 0 && (num & (~-num)) == 0;
Get max int Example
~-(1 << 31) & 0x7FFFFFFF Signed
Get min int Example
-~(~(1 << 31))
Check if factorial of 2
(n & (~-n)) == 0)
Get ABS value
(-3 ^ (-3 >> 31)) - (-3 >> 31)
if (x==a) x=b; if (x==b) x=a;
x = a ^ b ^ x;
Concat binary number
1 << 2 | 0 << 1 | 1 = 5 (101)
int ft_atoi(const char *str)
{
int to_dec;
int neg;
to_dec = 0;
neg = 1;
while (*str && (*str == ' ' || *str == '\t'))
str++;
while (*str && (*str == '+' || *str == '-'))
if (*str++ == '-')
neg = ~(neg - 1);
while (*str && *str >= '0' && *str <= '9')
to_dec = ((to_dec << 1) + (to_dec << 3)) + (*str++ & 0xF);
return (to_dec * neg);
}
@trankiloup
Copy link

Thanks for this sheecheat, so many tricks as usual.

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