Strings and hex values
Technical Note 76992
Architectures:
All
Component:
compiler
Updated:
2015/11/6 12:28
Introduction
An example: Sometimes you may want to write the character '4' using hexadecimal ascii value \x34 into a constant string like this:
const char test[] = "123\x3456";
The result you would like to have is "123456".
The behavior in this case is classed as "undefined" by ANSI, since you can never know if \x34 or \x345 will be used for the character. We do not have this strictly implemented in all the compilers so the behavior can truly be different for different compilers/versions.
One solution is of course to write like this:
const char test[] = '1','2','3','\x34','5','6','\0'};
But with a longer string it will unpleasant to write all the characters one by one.
A good solution is to use string concatenation like this:
const char test[] = "123\x34""56";
or like this:
const char test2[] = "123""\x34""56";
A similar solution for wide characters looks like this:
const wchar_t test3[] = L"123\x34"L"56";
or like this:
const wchar_t test4[] = L"123"L"\x34"L"56";