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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With