I have been trying to make a lookup table using the preprocessor that should return the binary representation for the values of a single byte. A string array basically with 256 elements. I can't seem to find any patterns thought so I'm wondering if it's even possible.
Asked
Active
Viewed 1,290 times
1
-
1I'd imagine this would be much easier with some simple code-generation (e.g. a Python/Perl script). – Oliver Charlesworth Mar 30 '14 at 17:57
-
I don't doubt that it's possible, but as you noticed, it's hard. It's probably easier to just generate the table and paste the final code in. – Thomas Mar 30 '14 at 17:57
-
"using the preprocessor" - please clarify. – Karoly Horvath Mar 30 '14 at 17:58
-
Using macros and patterns to generate it, pretty much like the classic number-of-set-bits-in-a-byte lookup table. – Veritas Mar 30 '14 at 18:00
-
@Veritas: could you provide a link for that? i'm not sure what you're talking about. how do you do that using the preprocessor? – Karoly Horvath Mar 30 '14 at 18:01
-
1http://stackoverflow.com/questions/18159425/bits-set-by-lookup-table-recursive-macro – Veritas Mar 30 '14 at 18:02
-
@BrianKelly What do you mean? I am trying to find a pattern to use with the preprocessor. How does posting what I've tried so far work? – Veritas Mar 30 '14 at 20:21
1 Answers
4
Here you go:
#include <stdio.h>
/* A macro for each bit */
#define B1(n) n "0", n "1"
#define B2(n) B1(n "0"), B1(n "1")
#define B3(n) B2(n "0"), B2(n "1")
#define B4(n) B3(n "0"), B3(n "1")
#define B5(n) B4(n "0"), B4(n "1")
#define B6(n) B5(n "0"), B5(n "1")
#define B7(n) B6(n "0"), B6(n "1")
/* Shorter way: macros add 2 bits */
#define C2(s) s"00", s"01", s"10", s"11"
#define C4(s) C2(s"00"), C2(s"01"), C2(s"10"), C2(s"11")
#define C6(s) C4(s"00"), C4(s"01"), C4(s"10"), C4(s"11")
static const char* Table256[256] =
{
/* B7("0"), B7("1") */
C6("00"), C6("01"), C6("10"), C6("11")
};
int main(int argc, const char* argv[])
{
int i;
for( i=0; i<256; ++i )
printf("%s ", Table256[i]);
printf("\n");
return 0;
}
The code is tested at ideone.

Alexey Kukanov
- 12,479
- 2
- 36
- 55