How to escape from hex to decimal

Apologies if this is an obvious question. I have searched the internet for an answer to this question and cannot find it. This does not apply to my code as such, it is curiosity on my part.

I am looking for testing my function to read the start and end bytes of a buffer.

If I declare a char array like this:

char *buffer;
buffer = "\x0212\x03";

      

Value STX12ETX

- Toggle between hexadecimal and decimal.

I am getting the expected error:

warning: hex escape sequence out of range [enabled by default]

      

I can test the code using all the hex values:

"\x02\x31\x32\x03"

      

I want to know if there is a way to escape the hexadecimal value to indicate that the following is a decimal value?

+3


source to share


3 answers


would something like this work for you?

char *buffer;

buffer = "\x02" "12" "\x03";

      

according to the standard:

§ 5.1.1.2 6. Adjacent string literals are concatenated.

§ 6.4.4.4 3. and 7. Each octal or hexadecimal escape sequence is the longest character sequence that can constitute an escape sequence.



  • escape characters:

  • \ '- single quote

  • \ "- double quote
  • \? - question mark?
  • \ - backslash \
  • \ octal digits
  • \ xhexadecimal digits

So the only way to do it is by string concatenation with precompiler concatenation (listing them one by one).

If you want to know more about how literals are constructed by the compiler take a look at §6.4.4.4 and §6.4.5, they describe how to construct character literals and string literals respectively.

+5


source


You can write

"\b12"

      

to represent the decimal value. Though you need to use a space after the hex values ​​for it to work.

buffer = "\x02 \b12\x03";

      



Or just 12

buffer = "\x02 12\x03";

      

Basically you need to add a blank character after the hex values ​​to indicate that it is a new value and not the same

+1


source


No, there is no way to end the hexadecimal escape except that it has an invalid character (for a hexadecimal value), but then that character is of course interpreted on its own.

Draft C11 says (in clause 6.4.4.4 14):

The [...] hexadecimal escape sequence is terminated with a non-hexadecimal character only.

Octal screens do not have this problem, they are limited to three octal digits.

+1


source







All Articles