texasbruce texasbruce - 4 months ago 34
C++ Question

How to initialize char array using hex numbers?

I use utf8 and have to save a constant in a char array:

const char s[] = {0xE2,0x82,0xAC, 0}; //the euro sign

However it gives me error:

test.cpp:15:40: error: narrowing conversion of ‘226’ from ‘int’ to ‘const char’ inside { } [-fpermissive]

I have to cast all the hex numbers to char, which I feel tedious and don't smell good. Is there any other proper way of doing this?


char may be signed or unsigned (and the default is implementation specific). You probably want

  const unsigned char s[] = {0xE2,0x82,0xAC, 0}; 


  const char s[] = "\xe2\x82\xac";

(a string literal is an array of char unless you give it some prefix)

See -funsigned-char (or -fsigned-char) option of GCC.

On some implementations a char is unsigned and CHAR_MAX is 255 (and CHAR_MIN is 0). On others char-s are signed so CHAR_MIN is -128 and CHAR_MAX is 127 (and e.g. things are different on Linux/PowerPC/32 bits and Linux/x86/32 bits). AFAIK nothing in the standard prohibits 19 bits signed chars.