Bitwise Operations
Shows how certain operators can be constructed using only bitwise operators. This is often actually much faster for the computer to compute.
/* *Examples of operations using only *The following operators: ! ~ & ^ | + << >> *By Ynori7 */ /////////////////////////////////////////////////// /////////////////////////////////////////////////// //return -1 int minusOne(void) { int x=0; return (~x); } /////////////////////////////////////////////////// /* * negate : return -x * Example: negate(5) = -5. */ int negate(int x) { return (~x)+1; } /////////////////////////////////////////////////// /* * copyLSB - set all bits of result to least significant bit of x * Example: copyLSB(5) = 0xFFFFFFFF (all 1's), copyLSB(6) = 0x00000000 */ int copyLSB(int x) { return !(x & 1)+(~0); } /////////////////////////////////////////////////// /* * fitsBits - return 1 if x can be represented as an * n-bit, two's complement integer. * 1 <= n <= 32 * Examples: fitsBits(5,3) = 0, fitsBits(-4,3) = 1 */ int fitsBits(int x, int n) { int y=x>>(n+(~0)); return !(y+1) | !y; } /////////////////////////////////////////////////// /* * isEqual - return 1 if x == y, and 0 otherwise * Examples: isEqual(5,5) = 1, isEqual(4,5) = 0 */ int isEqual(int x, int y) { return !(x ^ y); } /////////////////////////////////////////////////// /* * isPositive - return 1 if x > 0, return 0 otherwise * Example: isPositive(-1) = 0. */ int isPositive(int x) { return !(x>>31) & !!x; } /////////////////////////////////////////////////// /* * isGreater - if x > y then return 1, else return 0 * Example: isGreater(4,5) = 0, isGreater(5,4) = 1 */ int isGreater(int x, int y) { int a=x>>30, b=y>>30; int q=~(1<<31); int c=x&q, d=y&q; int z=a+(~b + 1); int h=c+(~d + 1); int p=!z; return ((!(z>>31) & !p) | (p & (!(h>>31)))) ^ !(x ^ y); } /////////////////////////////////////////////////// /* * logicalShift - shift x to the right by n, using a logical shift * Can assume that 1 <= n <= 31 * Examples: logicalShift(0x87654321,4) = 0x08765432 */ int logicalShift(int x, int n) { int y=(1<<31); int q= (~y) & x; int p= q>>n; int k= y&x; return ((k>>31) & (1<<(31+(~n+1)))) | p; } /////////////////////////////////////////////////// /* * leastBitPos - return a mask that marks the position of the * least significant 1 bit. If x == 0, return 0 * Example: leastBitPos(96) = 0x20 */ int leastBitPos(int x) { return (~x+1)&x; } /////////////////////////////////////////////////// /* * bitParity - returns 1 if x contains an odd number of 0's * Examples: bitParity(5) = 0, bitParity(7) = 1 */ int bitParity(int x) { int a = x ^ (x << 16); int b = a ^ (a << 8); int c = b ^ (b << 4); int d = c ^ (c << 2); int e = d ^ (d << 1); return !!(e & (1<<31)); }

This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
Download this code in plain text format here