Next revision | Previous revision |
new:bits [2018/02/18 19:00] – created korshun | new:bits [2018/02/19 12:29] (current) – korshun |
---|
====== Bit functions ====== | ====== Bit functions ====== |
| |
These functions allow you to work with variables as if they were arrays of bits. | These functions are for bit math. |
| |
* ''bool getbit(int a, int i)'' -- returns bit ''a[i]'' | ===== Powers of two ===== |
* ''void setbit(int a, int i)'' -- performs ''a[i] = 1'' | |
* ''void clrbit(int a, int i)'' -- performs ''a[i] = 0'' | * ''int npo2(int x)'' -- returns the next lowest power of 2 greater or equal to X. |
* ''void tglbit(int a, int i)'' -- performs ''a[i] = !a[i]'' | * ''int bitlog2(int x)'' -- returns the index of the highest used bit, aka integer binary logarithm. Useful to convert flags like ''1<<8 = 256'' back into ''8''. |
| |
| ===== Working with bit arrays ===== |
| |
| These functions allow you to work with variables as if they were arrays of bits: |
| |
| * ''bool getbit(int a, int i)'' -- returns bit ''a[i]''. |
| * ''int setbit(int a, int i)'' -- performs ''a[i] = 1'' and returns the result. |
| * ''int clrbit(int a, int i)'' -- performs ''a[i] = 0'' and returns the result. |
| * ''int tglbit(int a, int i)'' -- performs ''a[i] = !a[i]'' and returns the result. |
| |
| ===== Unsetting bit flags ===== |
| |
| ''void notflag(int flags, int flag)'' |
| |
| Bit flags can be applied using ''flags & SOMEFLAG''. But removing them requires a more complicated expression ''!(flags & SOMEFLAG)''. |
| |
| ''notflag(flags, SOMEFLAG)'' unsets SOMEFLAG, shorthand for ''!(flags & SOMEFLAG)''. |