Click here to Skip to main content
15,793,368 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The data string is ,

char arr[100] = "IN1::1209 OUT1::678 CURR1::4 KWh1::3"
collect the individual numeric data of 4 individuals from the above string and store it in a separate string and convert those individual data into hexadecimal value with leading zeroes.Can anyone help me write a C code for this?

What I have tried:

I have tried splitting individual data using strtok and collected the data and even tried to convert it to hex but not able to convert it with leading zeroes and I have no idea how to convert it to hex when I get a negative data so it won't convert to hex at all.
Updated 22-Dec-21 8:01am

Hex isn't complicated: it's the same a base 10 that you normally use, but based on 16 instead.
So to convert string values from decimal to hex is pretty easy:
1) Extract the numeric data from the string:
"1209", "678", "4", "3"
You know how to do that, you said so.
2) Convert those to integer values:
1209, 678, 4, 3
That's not complex either: atoi - C++ Reference[^]
3) Convert each integer to hex. That's also pretty easy, particularly with leading zeros:
3.1) Shift the top hex digit to the bottom position - the >> operator will do that if you use multiples of 4 for the shift count.
3.2) Use a binary AND to mask the value to just the lower four bits: that is a single hex digit.
3.3) Convert the hex digit to ASCII:
0 - '0'
 1 - '1'
 9 - '9'
10 - 'A'
11 - 'B'
15 - 'F'

3.4) Shift the original value left 4 places ready for the next digit - the << operator is your friend here.
4) Repeat until you have all digits.

Negatives convert automatically to hex values with the top bit set.

Give it a try manually, and you'll see what I mean.
Share this answer
Once you have converted the digit strings to integer values, you can convert them to HEX strings quite simply with one of the sprintf_s, _sprintf_s_l, swprintf_s, _swprintf_s_l | Microsoft Docs[^] functions.
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