Strings and hex values

Technical Note 76992

Arkitekturer:

All

Komponent:

compiler

Uppdaterad:

2015-11-06 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";

Det här innehållet finns tyvärr inte på svenska.

Vår webbplats finns främst på vårt koncernspråk engelska, förutom det innehåll för investerare som vi är lagstadgade att kommunicera på svenska. Vi rekommenderar att du besöker vår globala webbplats på engelska för att få en bättre upplevelse.

Vi stöder inte längre Internet Explorer. För att få bästa möjliga upplevelse av iar.com rekommenderar vi att du uppgraderar till en modern webbläsare som Chrome eller Edge.