Strings and hex values

Technical Note 76992



10/15/2015 1:09 PM


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";

Related Tech Notes

© IAR Systems 1995-2021 - All rights reserved.

We use cookies on this website to provide you with a better experience. You need to accept cookies to continue using this site. Cookies