Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C initialize array in hexadecimal values

I would like to initialize a 16-byte array of hexadecimal values, particularly the 0x20 (space character) value.

What is the correct way?

unsigned char a[16] = {0x20};

or

unsigned char a[16] = {"0x20"};

Thanks

like image 908
Kingamere Avatar asked Oct 31 '15 18:10

Kingamere


2 Answers

Defining this, for example

unsigned char a[16] = {0x20, 0x41, 0x42, };

will initialise the first three elements as shown, and the remaining elements to 0.

Your second way

unsigned char a[16] = {"0x20"};

won't do what you want: it just defines a nul-terminated string with the four characters 0x20, the compiler won't treat it as a hexadecimal value.

like image 56
Weather Vane Avatar answered Sep 21 '22 17:09

Weather Vane


There is a GNU extension called designated initializers. This is enabled by default with gcc

With this you can initialize your array in the form

unsigned char a[16] = {[0 ... 15] = 0x20};
like image 37
Raghu Srikanth Reddy Avatar answered Sep 21 '22 17:09

Raghu Srikanth Reddy