-2

This is Arduino code, but since it uses C syntax, and it's not Arduino-specific, I thought I'd ask here. I have a few values defined so:

#define PID_RPM 0x0C

Typically it's used as a hex number. But in one spot, I need to print the last 2 chars ("0C") as literal 2 ASCII chars "0C". Right now I do it with a switch and an explicit string "0C":

switch(pid){
  case PID_RPM: OBD.println("0C"); break;
  ...

How can I convert the PID_RPM define to get its last 2 chars as literal ASCII? Maybe, instead of using a define, use char variables to store the hex PID values, then format them as a string with sprintf?

1
  • how about printing the number in hex? OBD.printf("%02X", PID_RPM);? Commented Mar 22, 2022 at 16:58

1 Answer 1

0

The # operator inside of a function-like macro will turn the argument into a string. If you do this twice, you can turn the macro expansion of the argument into a string:

#include <stdio.h>

#define MACRO_TO_STR(x) #x
#define EXPANSION_TO_STR(x) MACRO_TO_STR(x)
#define PID_RPM 0x0C

int main()
{
  printf("MACRO_TO_STR(PID_RPM) = %s\n", MACRO_TO_STR(PID_RPM));
  printf("EXPANSION_TO_STR(PID_RPM) = %s\n", EXPANSION_TO_STR(PID_RPM));
}

Here is the output:

MACRO_TO_STR(PID_RPM) = PID_RPM
EXPANSION_TO_STR(PID_RPM) = 0x0C
4
  • Thanks, sounds good. Can the expansion do a substring, too, i.e. get just the last two chars (the actual meaningful hex values)? Commented Mar 22, 2022 at 6:21
  • @MrSparkly, the macro expansion cannot create substrings. But if you want to print the value in hex, you can just use printf("%02X", PID_RPM);. Commented Mar 22, 2022 at 7:40
  • @BartvanIngenSchenau Thanks, everything works. Commented Mar 22, 2022 at 9:52
  • the macro expansion creates a string literal, so yes, you can access a substring of that string. For a simple case like this, yes printf is probably a better option Commented Mar 22, 2022 at 15:14

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.