Create string with ESC command using HEX definition

516 Views Asked by At

I need to create string with special characer defined in HEX format:

std::string s = "\xFEd" ; 
error C2022: '65242' : too big for character

In case std::string s = "\xFE d" ; everything goes fine. How to tell string constructor treat "d" as string "d" and not numeric definition character in first case?

1

There are 1 best solutions below

0
On

You wrote in tags "visual C++" so I assume Microsoft compiler from Visual Studio.

Please review the reference and examples at this site. It tells what you should use, but it seems .. a little buggy. For example:

octal              \ooo
hexadecimal        \xhhh     <- note the 3 Hs
Unicode (UTF-8)    \uxxxx
Unicode (UTF-16)   \Uxxxxxxxx

and few pagedowns later, examples:

A hexadecimal escape sequence is a backslash followed by the character x, followed by a sequence of hexadecimal digits. An escape sequence that contains no hexadecimal digits causes compiler error C2153: "hex constants must have at least one hex digit". An escape sequence that has hexadecimal and non-hexadecimal characters is evaluated as the last non-hexadecimal character. The highest hexadecimal value is 0xff.

char c1 = '\x0050';  // char 'P'    <-- note 4 digits as 1 char
char c2 = '\x0pqr';  // char 'r'

Note the \x0pqr thing. Fun! I'd suspect compilation error, but no!

(..)

I've just found exact answer on MSDN: short info and long info. Exerpt from the latter:

Using embedded hexadecimal escape codes to specify string constants can cause unexpected results. The following example seeks to create a string literal that contains the ASCII 5 character, followed by the characters f, i, v, and e:

"\x05five"

The actual result is a hexadecimal 5F, which is the ASCII code for an underscore, followed by the characters i, v, and e. To get the correct result, you can use one of these:

"\005five"     // Use octal constant.  
"\x05" "five"  // Use string splicing.