binary constants (??)

Tom Stockfisch tps at chem.ucsd.edu
Sun Nov 19 06:38:30 AEST 1989


In article <305 at frf.omron.co.jp> jfriedl at 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 at chem.ucsd.edu



More information about the Comp.lang.c mailing list