Binary Constants: FOLLOWUP

Dean Inada dmi at peregrine.peregrine.com
Sun Nov 26 19:47:19 AEST 1989


In article <308 at frf.omron.co.jp> jfriedl at frf.omron.co.jp (Jfriedl) writes:
>Two weeks ago I posted a question about how to effect binary
>constants, as in the fictitious:
>	case 0b110011:	/* "bsr.n" opcode */
...
>	However, one response, reprinted here (without permission --
>hope it's ok), from uunet!peregrine.COM!dmi (Dean Inada) :
>> #define DTOB(N)	((N)%8 + (N)/125%64 + ((N)/15625%512&0700))
                                                        ^^^^
Note that the %512 is superfluous here. 

Or,
#define DTOB(N)	((N)*9/5%16 + ((N)*9/3125&0xf0))

Can anyone reduce this to one eval of (N)?

>> #define H(N)	(0x ## N)
>> #define HTOB(N)	(\
>> 	((\
>> 		((\
>> 			((\
>> 				(N)\
>> 			*0x15)&0x21221881)%0xffff%0x1ff\
>> 		*0x1001)&0x9216d)%0x1ff\
>> 	*0x201)&c200ff)%0x7ff\
>> )/*note: evaluates arg only once*/
>
>Inspired, I'd say.  Having absolutely NO clue to the above, I asked for
>the derivation (which, as it turns out, I didn't understand either).
You might try tracing the intermediate values for
0x1, 0x10, 0x100, ... ,0x10000000

>It's somewhat long, but if you want it, let me know and I'll pass it
>along.
If you do pass it along, let me know where.

>This new macro, above, would be much more compact if C had an operator
>which meant "fold bits, keeping every third bit".  Mmmm, maybe
>if we sue..... (-:

Picking up the gauntlet:  -)
#define _CONV_O2B(N)	(\
	(((((\
 	(N)%01777	/* 100001 */\
 	*04000001&050001545)%03777	/* 100011 */\
	*04000001&010420001443)%07777	/* 100111 */\
	*010001&030000547)%0777	/*   111111 */\
	*02001&0200477)%0777	/* 10111111 */\
	*0401&0200277)%01777	/* 11111111 */\
)

Only 8 bits worth, and no effort to optimize like the hex version,
but that didn't get very far anyway.  Anyone else care to try?



More information about the Comp.lang.c mailing list