0

I need to represent an arbitrary sequence of bytes as a C++ string literal, but in the typical case where it is mostly an ASCII string, keep it as readable as reasonably possible. The obvious way to do this is as a string literal with escape sequences where necessary, but this runs into a problem.

Consider "\xaaa". The \x escape sequence can take at most two hexadecimal digits. I would therefore expect the compiler to take those two hexadecimal digits, consider the escape sequence to be complete, and go back to reading literal characters. Instead, Microsoft C++ says error C2022: '2730': too big for character.

The same problem happens with octal e.g. "\5555".

As far as I can see, perhaps the least awkward solution is to stop and restart the string literal, e.g. "\xaa" "a".

Is there a more compact/idiomatic solution?

rwallace
  • 31,405
  • 40
  • 123
  • 242
  • 1
    *"The `\x` escape sequence can take at most two hexadecimal digits."* -- not true. According to [cppreference.com](https://en.cppreference.com/w/cpp/language/escape#Notes): "Hexadecimal escape sequences have no length limit and terminate at the first character that is not a valid hexadecimal digit." – JaMiT Sep 03 '23 at 04:53
  • @JaMiT Right, fair correction; I should have said, can *usefully* take at most two. – rwallace Sep 03 '23 at 04:56
  • 1
    *"Is there a more compact/idiomatic solution?"* -- well, you could remove the space between the literals, but I don't see how you could hope to make it more compact than adding only two characters (and FWIW, this approach is mentioned in [cppreference.com](https://en.cppreference.com/w/cpp/language/string_literal#Notes)). But maybe someone can. Never say never. – JaMiT Sep 03 '23 at 04:58

0 Answers0