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

很抱歉,该页面尚未翻译成中文。

如果您有任何问题,请联系我们的中国团队

We do no longer support Internet Explorer. To get the best experience of iar.com, we recommend upgrading to a modern browser such as Chrome or Edge.