Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Last active April 15, 2023 19:03
Show Gist options
  • Save unitycoder/32a9c41fc1947ab99148 to your computer and use it in GitHub Desktop.
Save unitycoder/32a9c41fc1947ab99148 to your computer and use it in GitHub Desktop.
Bitshift CheatSheet Bitconverter BitWise
// MULTIPLY
a=1
a << 1 == a*2 [ a=2 ]
a << 2 == a*4 [ a=4 ]
a << 3 == a*8 [ a=8 ]
1 << 1 == 1*2 [ a=2 ]
1 << 2 == 1*4 [ a=4 ]
1 << 3 == 1*8 [ a=8 ]
x/255 == (x+1+((x+1)>>8))>>8 // integer div 255 for [0..65790)
// bitconverter replacement
UInt16 value = 32;
byte[] array = BitConverter.GetBytes(value);
var slow = BitConverter.ToUInt16(array, 0)
var fast = (ushort)((array[0 + 1] << 8) + array[0])
UInt32 value = 32;
byte[] array = BitConverter.GetBytes(value);
var slow = BitConverter.ToUInt32(array, 0);
var fast = (UInt32)(array[0] | (array[1] << 8) | (array[2] << 16) | (array[3] << 24));
// ref
http://lab.polygonal.de/2007/05/10/bitwise-gems-fast-integer-math/
// benchmarks
https://jsperf.com/math-floor-vs-math-round-vs-parseint/33
// bit manipulation cheat sheet
https://www.cheatography.com/miracoli/cheat-sheets/bitmanipulation/
// check for power of 2 : https://youtu.be/3vUzT7JFMVc?t=2137
bool isPow2(u32 value)
{
return ((value & ~(value-1)) == value);
}
// float tricks
https://randomascii.wordpress.com/2012/01/23/stupid-float-tricks-2/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment