Prince Kishore Prince Kishore - 1 month ago 5
C Question

How to char[] to Hex? C

So I have kind of hit a road block in my project.
What I am trying to do is figure out a way to take four individual binary characters which are representing flags. Now my last task was to take these four flags and put them in a char[] which wasn't difficult at all. But now, I want to take the four and convert it to a hex.

So for example:

O = 1;
C = 1;
Z = 0;
N = 0;

char flags[5];
flags[0] = O;
flags[1] = C;
flags[2] = Z;
flags[3] = N;


Now I wanted to make a string or something i can convert the above to a Hex. So for example I want to have 1100 converted to a hex which is 0xC

Now I have tried to make it in to a string first then parse it but I'm confused and lost now. I just can't see to get the right output.

Answer Source
int flags;
flags = (O << 3) | (C << 2) | (Z << 1) | N;
sprintf(buffer, "0x%02X", 0xff & flags);

flags is defined a single int-variable containing all your flags.

buffer is a char array of sufficient size.

The 0xff & .. is not needed in this case, but might be some day if your flags variable can get negative and you still only want to have a one byte output (2 hex digits).