Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize char array using hex numbers?

Tags:

c++

unicode

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?

like image 963
SwiftMango Avatar asked Oct 31 '13 19:10

SwiftMango


People also ask

How do you initialize a character array?

You can initialize a one-dimensional character array by specifying: A brace-enclosed comma-separated list of constants, each of which can be contained in a character. A string constant (braces surrounding the constant are optional)

Can we initialize char to 0?

To initialize a char in Java, we can use any char value such as an empty char, or \0 , or even a char value itself.

How do you add two hexadecimal numbers in Python?

In python, there are inbuilt functions like hex() to convert binary numbers to hexadecimal numbers. To add two hexadecimal values in python we will first convert them into decimal values then add them and then finally again convert them to a hexadecimal value. To convert the numbers make use of the hex() function.


1 Answers

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

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

or

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

or with many recent compilers (including GCC)

  const char s[] = "€";

(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.

like image 189
Basile Starynkevitch Avatar answered Sep 19 '22 02:09

Basile Starynkevitch