C initialize array in hexadecimal values

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.


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

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

or

unsigned char a[16] = "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20";