Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can operate bit-by-bit (as Mark Byers suggested), by extracing every bit which will be slow.</p> <p>Or you could accelerate process and use 2d lookup tables that store results, say, for two 4-bit operands and operate on those. You'll need less extractions than if you were operating on bits.</p> <p>YOu can also do everything using addition, substraction and >= operation. Every bitwise operation can be unrolled into something like this using macros:</p> <pre><code>/*I didn't actually compile/test it, it is just illustration for the idea*/ uint16 and(uint16 a, uint16 b){ uint16 result = 0; #define AND_MACRO(c) \ if (a &gt;= c){ \ if (b &gt;= c){\ result += c;\ b -= c;\ }\ a -= c;\ }\ else if (b &gt;= c)\ b -= c; AND_MACRO(0x8000) AND_MACRO(0x4000) AND_MACRO(0x2000) AND_MACRO(0x1000) AND_MACRO(0x0800) AND_MACRO(0x0400) AND_MACRO(0x0200) AND_MACRO(0x0100) AND_MACRO(0x0080) AND_MACRO(0x0040) AND_MACRO(0x0020) AND_MACRO(0x0010) AND_MACRO(0x0008) AND_MACRO(0x0004) AND_MACRO(0x0002) AND_MACRO(0x0001) #undef AND_MACRO return result; } </code></pre> <p>You'll need 3 variables to implement this.</p> <p>Every bitwise operation will revolve around macros similar to AND_MACRO - you compare remaining values of a and b to the "mask" (which is "c" parameter). then add mask to the result in the if branch that is suitable for your operation. And you subtract mask from values, if bit is set. </p> <p>Depending on your platform, it may be faster than extracting every bit using % and / , and then putting it back using multiplication.</p> <p>See for yourself whichever is better for you.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload