C initialize array in hexadecimal values
Solution 1
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};
Solution 2
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.
Solution 3
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";
Solution 4
The first way is correct, but you need to repeat the 0x20,
sixteen times. You can also do this:
unsigned char a[16] = " ";
Solution 5
I don't know if this is what you were looking for, but if the size of the given array is going to be changed (frequently or not), for easier maintenance you may consider the following method based on memset()
#include <string.h>
#define NUM_OF_CHARS 16
int main()
{
unsigned char a[NUM_OF_CHARS];
// initialization of the array a with 0x20 for any value of NUM_OF_CHARS
memset(a, 0x20, sizeof(a));
....
}
Kingamere
Updated on April 17, 2020Comments
-
Kingamere about 4 years
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