Click here to Skip to main content
15,900,725 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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

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.
 
Share this answer
 
Comments
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'.
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.
 
Share this answer
 
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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900