1

I'm working with a game engine that uses escape codes in strings to perform commands such as setting color. eg to set the color to red, you write "Red text:\x81\xFF\x00\x00\xFFhello!" (0x81, red, green, blue, alpha).

Is it possible to create a macro like TEXT_COLOR(r,g,b,a) such that TEXT_COLOR(255,0,0,255) would expand to "\x81\xFF\x00\x00\xFF" for use in constant strings?

1
  • 2
    You can certainly do it with TEXT_COLOR(FF,00,00,FF) Commented Mar 14, 2021 at 0:06

1 Answer 1

2

It takes a mix of token pasting and stringification in different macros, but, yeah, it's possible using base-16 numbers:

#include <stdio.h>

#define TEXT_COLOR2(r,g,b,a) "\x81" #r #g #b #a
#define TEXT_COLOR(r,g,b,a) TEXT_COLOR2(\x ##r, \x ##g, \x ##b, \x ##a)

int main(void) {
  char s[] = "Red text:" TEXT_COLOR(FF, 00, 00, FF) "hello!";
  for (const char *c = s; c < s + sizeof(s); c++) {
    printf("\\x%02hhX", *c);
  }
  putchar('\n');
  return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.