1. ## Hex to binary

Hi everyone,
I would like check with you all, how do I convert hex to binary in c ?

2. How do you print integer value using its binary representation? Or what?
Because all numbers are stored in the computer internally in the binary format...

Hint
uns_var & (1 << i) gives you the i-th bit value

or
(uns_var >> i)&1 - so the result will be 0 or one

if i is zero you will get less significant bit

3. Hi vart,
Actually I'm having a function that only take in unsigned char in binary format. I need to convert my hex data into binary format first in order to pass the parameter to the function. So I was wondering how can I convert the hex format to bin format.

4. Do you mean the function receives array of 0 and 1? Or what?

There is no such thing as hex data or binary data...

unsigned char is a number from 0 to 255
If you convert it to string - you can choose the different bases for this representation... But this will be string representation of the number...

Like number 16 I can conver to string
"16" or
"0x10"
or
"10000"
but when I store it as a number it just a number

So I really don't understand what you are trying to do...

5. I believe I might have confused you. What I really mean is that I have a char array which is in hex format. e.g FF . Therefore I would like to convert it into char array which is in binary format, 0 or 1. so is there a way to do that ?

6. there are several ways to do it
for example switch
Code:
```const unsigned char* hex2bin(unsigned char val)
{
switch(val)
{
case '0': return "0000";
case '1': return "0001";
...
case 'F': return "1111";
}
retrun NULL;
}```
or converting hex-string to number, then converting number to binary string using bitshift operations

7. If you want to go straight from hex string to bin string, use what vart said. Else, if you need to do calculations, go through int. The following example should work on null terminated char arrays. Haven't tested it though.
Code:
```int hex_to_int(const char *hex_string) {
int return_val = 0;
while (*hex_string != '\0') {
if (*hex_string <= '9') {
return_val = return_val * 16 + *hex_string - '0';
} else if (*hex_string <= 'F') {
return_val = return_val * 16 + *hex_string -  'A' + 10;
} else {
return_val = return_val * 16 + *hex_string - 'a' + 10;
}
hex_string++;
}
return return_val;
}```
Then you can go to binary later.

8. Thanks alot vart, one last thing. You said that it possible to convert it to number. If let say I would want to convert it to number, how can it be done ?

9. oh thanks coder.