简体   繁体   English

将char数组中的char转换为ANSI C中自己的char数组

[英]Convert char in char array to its own char array in ANSI C

I have a char array representing a double precision floating point number in hex form. 我有一个char数组,以十六进制形式表示双精度浮点数。

char *hex = ""402499999999999A"

I want to extract each char in hex as its own char array and read it into an unsigned int num . 我想将hex每个char提取为自己的char数组,并将其读入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. 但这并没有给我第4个char作为单独的char数组,而是给了我第4个位置的sub char数组,我想这是因为数组是由第一个元素的指针给定的。

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. 我看了看strcpy ,看来我只能复制前n个字符,所以这不好。

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). 可以通过错误处理进行改进(例如,检测“ src [i]”是否包含有效/合理的字符)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM