Skip to content

How to combine 4 characters into 1 character

An answer to this question on Stack Overflow.

Question

This is driving me nuts because I don't know the magic words to search for to find a solution.

I initialize:

unsigned char foo[] = {'0', 'x', '1', '1'};

unsigned char bar[] = {'\0'};

Essentially I want bar[0] to be equal to the value 0x11. How do I do that? I feel stupid and I'm pretty sure there's a simple solution but I can't figure it out. I tried

memcpy(&bar[0], &foo[0], 1);

But that just makes bar[0] have the value of 0x30, which is the ascii value of the '0' character.

Any help/hints?

Answer

The notation 'a' converts the character a to a number, as defined by the ASCII system

Therefore,

unsigned char foo[] = {'0', 'x', '1', '1'};

is actually

unsigned char foo[] = {48, 120, 49, 49};

or, in hex

unsigned char foo[] = {0x30, 0x78, 0x31, 0x31};

So, what you need is to simply

unsigned char bar[] = { 0x11 };

or

bar[0] = 0x11;

if you already have bar defined somewhere.