I have a decimal number and we have converted it to hex and have stored in a hex array. After that I added a "0x" to this number (in fact char array). Now I want to convert this hex number (in char array) to Uint8_t and then print it. The first question is how this convert can be done and the second one is that in the process of printing, what print format (%02x, %d, %s , and ...) should be used?
Asked
Active
Viewed 108 times
-1
-
1It's not clear what exactly you're asking. What is a "hex array"? What does it mean to "add 0x to this number (in fact char array)? What do you mean by "convert char array to uint8_t"? What's the goal -- represent the data in a different form, print it, or both? Can you include code that you've already written, and a desired output for a given input? – Paul Hankin Oct 22 '22 at 11:36
-
It is unclear what a "hex array" is. Do you mean something like `char array[] = "0xA5";`? If that is the case, then please [edit] the question to provide an example. This will make your question clearer. – Andreas Wenzel Oct 22 '22 at 12:00
-
As for the second question, you forgot to say what output you want. – Weather Vane Oct 22 '22 at 12:09
-
Convert hex chars by calling strtol. Print using whichever output base you need. – stark Oct 22 '22 at 12:37
-
@PaulHankin In short, what I currently have in my code is a char array that contains the value of "0x8A" (8A is just an example). Now I want to convert it to uint8_t type so that, for example, I have a value in the form of 0x8A in a variable with the uint8_t type. – sh.sagheb Oct 23 '22 at 10:23
-
@WeatherVane In short, what I currently have in my code is a char array that contains the value of "0x8A" (8A is just an example). Now I want to convert it to uint8_t type so that, for example, I have a value in the form of 0x8A in a variable with the uint8_t type. – sh.sagheb Oct 23 '22 at 10:25
-
`uint8_t x = strtol(arr, 0, 16); printf("0x%02x", x);` – Paul Hankin Oct 23 '22 at 10:31
1 Answers
1
This example converts the hex string to an integer:
#include <stdio.h>
int main(void)
{
int val;
char str[] = "0x12";
int res = sscanf(str, "%i", &val);
printf("res=%d val=%d\n", res, val);
}
Program output
res=1 val=18
The %i
format is used in scanf
function family to accept input in decimal, octal (with a leading 0) or hex (with leading 0x). If you only want to accept decimal use %d
or %u
.

Weather Vane
- 33,872
- 7
- 36
- 56