Home > Enterprise >  How can I replicate compile time hex string interpretation at run time!? c
How can I replicate compile time hex string interpretation at run time!? c

Time:10-07

In my code the following line gives me data that performs the task its meant for:

const char *key = "\xf1`\xf8\a\\\x9cT\x82z\x18\x5\xb9\xbc\x80\xca\x15";

The problem is that it gets converted at compile time according to rules that I don't fully understand. How does "\x" work in a String?

What I'd like to do is to get the same result but from a string exactly like that fed in at run time. I have tried a lot of things and looked for answers but none that match closely enough for me to be able to apply.

I understand that \x denotes a hex number. But I don't know in which form that gets 'baked out' by the compiler (gcc).

What does that ` translate into?

Does the "\a" do something similar to "\x"?

CodePudding user response:

If you want to translate "escape" codes in strings that you get as input at run-time then you need to do it yourself, explicitly.

One way is to read the input into one string. Then copy the characters from that source string into a new destination string, one by one. If you see a backslash then you discard it, fetch the next character, and if it's an x you can use e.g. std::stoi to convert the next few characters into its corresponding integer value, and append that number to the destination string (either adding it with std::to_string, or using output string streams and the normal "output" operator <<).

CodePudding user response:

This is indeed provided by the compiler, but this part is not member of the standard library. That means that you are left with 3 ways:

  • dynamically write a C source file containing the string, and writing it on its standard output. Compile it and (providing popen is available) execute it from your main program and read its input. Pretty ugly isn't it...
  • use the source of an existing compiler, or directly its internal libraries. Clang is probably a good starting point because it has been designed to be modular. But it could require a good amount of work to find where that damned specific point is coded and how to use that...
  • just mimic what the compiler does, and write your own parser by hand. It is not that hard, and will learn you why tests are useful...

If it was not clear until here, I strongly urge you to use the third way ;-)

  • Related