Can you shorten this macro?

F

Francois Grieu

Quiz:

Find (one of) the shortest C89/C90 macro, behaving as a pure function,
which, given x = 1<<b with b in [0..7], returns b.
F(1) evaluates to 0
F(2) evaluates to 1
F(4) evaluates to 2
F(8) evaluates to 3
F(16) evaluates to 4
F(32 evaluates to 5
F(64) evaluates to 6
F(128) evaluates to 7
The macro must not depend on headers (e.g. <math.h>) or code/constants
outside the macro.

So far my best attempt is 39 chars long, including
17 for what (I think is) obligatory:
#define F(x)((x))

I guess it can be beaten.


Francois Grieu

Caution: spoiler follows
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
#define F(x)((0xE4FD71B>>(x)%11*3)+5&7)
 
H

Harald van Dijk

Quiz:

Find (one of) the shortest C89/C90 macro, behaving as a pure function,
which, given x = 1<<b with b in [0..7], returns b.
[...]
So far my best attempt is 39 chars long

32 characters:

#define F(x)(0x675a16%((x)+9)%8)
 
H

Harald van Dijk

Quiz:

Find (one of) the shortest C89/C90 macro, behaving as a pure function,
which, given x = 1<<b with b in [0..7], returns b.
[...]
So far my best attempt is 39 chars long

32 characters:

#define F(x)(0x675a16%((x)+9)%8)

31 characters:

#define F(x)(6773270%((x)+9)%8)

:)
 
F

Francois Grieu

Harald van Dijk wrote :
Quiz:

Find (one of) the shortest C89/C90 macro, behaving as a pure function,
which, given x = 1<<b with b in [0..7], returns b.
[...]

32 characters:

#define F(x)(0x675a16%((x)+9)%8)

Amazing! Here is a slightly shorter (31 characters) derivative:
#define F(x)(6773270%((x)+9)&7)

Francois Grieu
 
F

Francois Grieu

Harald said:
Quiz:

Find (one of) the shortest C89/C90 macro, behaving as a pure function,
which, given x = 1<<b with b in [0..7], returns b.
[...]
So far my best attempt is 39 chars long

31 characters:

#define F(x)(6773270%((x)+9)%8)

:)

On the same line of thought (not shorter)
#define F(x)(478414%((x)+37)&7)

Francois Grieu
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top