I have a char array representing a double precision floating point number in hex form.
char *hex = ""402499999999999A"
I want to extract each char in hex
as its own char array and read it into an unsigned int num
. For example, I tried
sscanf((char *)&hex[3], "%X", &num);
But this doesn't give me the 4th char as an individual char array, it gives me the sub char array from the 4th position on, which I suppose is because arrays are given by the pointer of their first element.
Is there a better way to do this? I looked at strcpy
and it seems that I can only copy the first n chars, so that's no good.
You can do this in many ways. One way is as follows (which is the correct way of how you were doing it):
char only_1_char[2] = {'\0', '\0'};
only_1_char[0] = hex[3];
sscanf(only_1_char, "%X", &num);
and a more efficient solution:
if (hex[3] <= '9')
num = hex[3] - '0';
else
num = hex[3] - 'A' + 10;
This is just a sample, though. In truth you need to take care of invalid input and lower cases if that is a possibility.
Try something like this:
for(i = 0; src[i] != 0; i++) {
if(src[i]) <= '9') {
dest[i] = src[i] - '0';
} else {
dest[i] = toupper(src[i]) - 'A' + 10;
}
}
It can be improved with error handling (eg detect if "src[i]" contains a valid/sane character).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.