bithacks.h

Go to the documentation of this file.
00001 /* 
00002 ** bithacks.h - bit hacks macros. v1.0
00003 **
00004 ** Peteris Krumins (peter@catonmat.net)
00005 ** http://www.catonmat.net  --  good coders code, great reuse
00006 **
00007 ** This file is explained in the following article:
00008 ** http://www.catonmat.net/blog/bit-hacks-header-file
00009 **
00010 ** Released under the MIT license.
00011 */
00012 
00013 #ifndef BITHACKS_H
00014 #define BITHACKS_H
00015 
00016 #define HEXIFY(x) 0x##x##LU
00017 
00018 #define B8IFY(x) (((x&0x0000000FLU)?1:0)  + \
00019                   ((x&0x000000F0LU)?2:0)  + \
00020                   ((x&0x00000F00LU)?4:0)  + \
00021                   ((x&0x0000F000LU)?8:0)  + \
00022                   ((x&0x000F0000LU)?16:0) + \
00023                   ((x&0x00F00000LU)?32:0) + \
00024                   ((x&0x0F000000LU)?64:0) + \
00025                   ((x&0xF0000000LU)?128:0))
00026 
00027 #define B8(x) ((unsigned char)B8IFY(HEXIFY(x)))
00028 
00029 /*
00030 ** Bit hack routines. See the following article for explanation:
00031 ** http://www.catonmat.net/blog/low-level-bit-hacks-you-absolutely-must-know
00032 **
00033 */
00034 
00035 /* test if x is even */
00036 #define B_EVEN(x)        (((x)&1)==0)
00037 
00038 /* test if x is odd */
00039 #define B_ODD(x)         (!B_EVEN((x)))
00040 
00041 /* test if n-th bit in x is set */
00042 #define B_IS_SET(x, n)   (((x) & (1<<(n)))?1:0)
00043 
00044 /* set n-th bit in x */
00045 #define B_SET(x, n)      ((x) |= (1<<(n)))
00046 
00047 /* unset n-th bit in x */
00048 #define B_UNSET(x, n)    ((x) &= ~(1<<(n)))
00049 
00050 /* toggle n-th bit in x */
00051 #define B_TOGGLE(x, n)   ((x) ^= (1<<(n)))
00052 
00053 /* turn off right-most 1-bit in x */
00054 #define B_TURNOFF_1(x)   ((x) &= ((x)-1))
00055 
00056 /* isolate right-most 1-bit in x */
00057 #define B_ISOLATE_1(x)   ((x) &= (-(x)))
00058 
00059 /* right-propagate right-most 1-bit in x */
00060 #define B_PROPAGATE_1(x) ((x) |= ((x)-1))
00061 
00062 /* isolate right-most 0-bit in x */
00063 #define B_ISOLATE_0(x)   ((x) = ~x & ((x)+1))
00064 
00065 /* turn on right-most 0-bit in x */
00066 #define B_TURNON_0(x)    ((x) |= ((x)+1))
00067 
00068 /*
00069 ** more bit hacks coming as soon as I post an article on advanced bit hacks
00070 */
00071 
00072 #endif
00073 

ContextLogger2—ContextLogger2 Logger Daemon Internals—Generated on Mon May 2 13:49:51 2011 by Doxygen 1.6.1