Reverse an ASCII string using C macros only

1k Views Asked by At

I am trying to output Hebrew words in Pebble that are given as ISO-8859-8 encoded char* in C code, however I need to turn them into ISO-8859-8-L encoded strings. This basically means reversing the strings:

"ABC D" => "D CBA"

The input strings are 8-bit ASCII (no multi-byte or unicode). I know how to do in-place reversion of the strings in C code, but then I need to reverse all strings in the init() function, so I wonder if there's a way to define a C macro to do it.

1

There are 1 best solutions below

1
NoSeatbelts On

I am not aware of any use of the CPP for reversing a string.

You could certainly use a function-like macro, as below.

#define rev_str(string, len) do {               \
    int i;                                      \
    for(i = 0; i < len>>1; ++i) {               \
        const uint8_t t = string[len - i - 1]]; \
        string[len - i - 1] = string[i];        \
        string[i] = t;                          \
    }                                           \
} while(0)

But then I don't see what advantage this has over being an inline function.

On the other hand, if you want to defer this to compile-time (and wanting it to use only macros makes me think you might), I believe you would need something beyond the scope of the CPP, such as C++'s template metaprogramming.