Path: utzoo!yunexus!ists!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!ucsd!chem.ucsd.edu!tps From: tps@chem.ucsd.edu (Tom Stockfisch) Newsgroups: comp.lang.c Subject: Re: binary constants (??) Keywords: macro, constant, binary Message-ID: <602@chem.ucsd.EDU> Date: 18 Nov 89 19:38:30 GMT Article-I.D.: chem.602 References: <305@frf.omron.co.jp> Reply-To: tps@chem.ucsd.edu (Tom Stockfisch) Organization: Chemistry Dept, UC San Diego Lines: 71 In article <305@frf.omron.co.jp> jfriedl@frf.omron.co.jp (Jfriedl) writes: >In some cases, I find it would be much more natural to represent >integral constants in binary, ... > #define FLAG_A 00000001000 > #define FLAG_B 00000010000 > #define FLAG_C 00000100000 > #define FLAG_D 00001000000 > #define FLAG_E 00010000000 > #define FLAG_F 00100000000 > #define FLAG_MASK 00111111000 >rather more immediately obvious than > #define FLAG_A 0x0008 > ... Here are different ways I have done it: (1) Brute Force (useful only for a small range, like 0-15) /* base2.h */ # define B0000 0 # define B0001 1 ... # define B1111 15 (2) Portable Macro (lots of typing required) # define B8(a,b,c,d,e,f,g,h) ( \ ((((((((((((a) << 1) | (b) ) << 1 ) | (c) ) \ << 1 ) | (d) << 1 ) | (e) << 1 ) | (f) ) \ << 1 ) | (g) ) << 1 ) | (h) \ ) ... x &= B8(1,1,1,1,1,1,1,1); /* mask off lower 8 bits */ # define FLAG_MASK2 B8( 0,0,1,1,1,1,1,1,0,0 ) (3) Name That Bit (useful for one bit set) # define # define FLAG_A (1<<3) # define FLAG_B (1<<4) ... or # define Bit(b) (1 << (b)) ... # define FLAG_A Bit(3) # define FLAG_B Bit(4) ... (4) C Idiom Memorize the bit patterns of 0x0 thru 0xf and then write your constants as, e.g. x &= 0xf; /* mask lower nybble */ # define FLAG_MASK 0x1f8 If the bit pattern is really more lucid than the hex representation, add a comment: # define MASK 0x41416 /* bin 100 0001 0100 0001 0110 */ For constants with 1 bit set I tend to use (3), and for the rest I just use (4). -- || Tom Stockfisch, UCSD Chemistry tps@chem.ucsd.edu