Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top