Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for macro converting decimal value into its hex representation

In one of my projects I'm defining the current version as a decimal value, which looks something like that:

#define MINOR_VERSION 13

In order to be able to output the version when asked for it, I need to get the hex representation into a string. Currently I'm working with sprintf(), which basically looks like this:

char buffer[3];
sprintf(buffer, "%2x", MINOR_VERSION);
// output buffer

This has a couple of drawbacks, one of which is the increased code size as sprintf() needs to be included. Furthermore the value gets calculated during runtime, which is wasted effort anyway. Both of these issues are critical to me, as I'm working with microcontrollers here.

Maybe I'm missing the totally obvious, but I can't come up with a nice and clean macro doing the conversion for me. In principle I need a way to convert 13 into its hex representation (2 digits, without the typically preceding 0x) 0d during compilation.

What would you suggest?

like image 287
Karol Babioch Avatar asked Dec 30 '13 00:12

Karol Babioch


1 Answers

Flip the problem around, and define the version as a hexadecimal. When you need to use it as a string, use the answer from here to convert it to a string. Then you can do things like this:

#include <stdio.h>

#define VERSION 0xd
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)

int main() {
  printf("hello " TOSTRING(VERSION) "\n");
  printf("%d\n", VERSION);
}
like image 85
razeh Avatar answered Sep 29 '22 05:09

razeh