15,900,725 members
See more:
I have a file with hex values saved as sample.txt which has

0x5f05 0x3c75 0x9c53

the file can have more hex values (i dont know the exact number of the hex values).
Now I need to convert it to a unsinged short int array as

unsigned short int table[] ={0101111100000101,0011110001110101,1001110001010011}

How can i achieve this? Thanks for your time and for your effort and happy new year!

What I have tried:

All the info is mentioned above
Posted
Updated 12-Mar-23 8:01am

## Solution 1

A quick google search: c convert string hex to binary - Google Search[^] found many results, like: How to convert a hexadecimal string to a binary string in C[^] . If not happy with this one, there are many others to choose from.

FKV3 2-Jan-23 10:17am
I have found them before posting here but the problem is that i have a different case, my case is to read hex values that are type of 0x like 0x9c53 and not just 9c53 , and i must read them from an external file. Thats why i end up asking for help here
Graeme_Grant 2-Jan-23 10:36am
strip unwanted characters. Hex is only 0123456789abcdef ... only decode after the 'x'.

## Solution 2

You can use strtoul[^] to convert strings to unsigned integers.

fgets[^] can be used to read strings from the file. The page has sample code for doing that.

## Solution 3

You might try iterating over the strings with isxdigit() function which will only consider hex digits 0-9 and a-f/A-F, (case doesn't matter).

Then convert each char digit returned by isxdigit on each iteration.

See the man page, string chars must be unsigned char so you might have to cast...something like:
`isxdigit((unsigned char)inputStr[i])`

in a loop.