将16进制的字符串转换成16进制,c代码实现
时间: 2024-09-25 19:09:09 浏览: 51
在C语言中,将一个十六进制字符串转换成整数可以使用标准库函数`strtol`或者`strtoul`处理字符串并指定基数(这里是16)。以下是一个简单的示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 函数原型声明,用于处理大小写混合的十六进制字符串
long long int hex_to_int(const char *hex_str);
// 实现函数,将十六进制字符串转换为长整型
long long int hex_to_int(const char *hex_str) {
long long int value = 0;
int len = strlen(hex_str);
// 遍历字符串,每两位作为一个十六进制数字
for (int i = 0; i < len; i += 2) {
if (i + 1 < len) {
// 检查字符是否合法,并转换为十六进制值
char hex_digit1 = tolower(hex_str[i]);
char hex_digit2 = tolower(hex_str[i + 1]);
if ('0' <= hex_digit1 && hex_digit1 <= '9')
value = value * 16 + hex_digit1 - '0';
else if ('a' <= hex_digit1 && hex_digit1 <= 'f')
value = value * 16 + hex_digit1 - 'a' + 10;
else if ('A' <= hex_digit1 && hex_digit1 <= 'F')
value = value * 16 + hex_digit1 - 'A' + 10;
if ('0' <= hex_digit2 && hex_digit2 <= '9')
value = value * 16 + hex_digit2 - '0';
else if ('a' <= hex_digit2 && hex_digit2 <= 'f')
value = value * 16 + hex_digit2 - 'a' + 10;
else if ('A' <= hex_digit2 && hex_digit2 <= 'F')
value = value * 16 + hex_digit2 - 'A' + 10;
} else {
// 如果字符串长度是奇数,处理最后一个单独的字符
if ('0' <= hex_str[i] && hex_str[i] <= '9')
value = value * 16 + hex_str[i] - '0';
else if ('a' <= hex_str[i] && hex_str[i] <= 'f')
value = value * 16 + hex_str[i] - 'a' + 10;
else if ('A' <= hex_str[i] && hex_str[i] <= 'F')
value = value * 16 + hex_str[i] - 'A' + 10;
}
}
return value;
}
int main() {
const char *hex_str = "ffAB";
long long int decimal_value = hex_to_int(hex_str);
printf("Hexadecimal string %s converted to decimal is: %lld\n", hex_str, decimal_value);
return 0;
}
```
这个代码首先定义了一个`hex_to_int`函数,它遍历输入的十六进制字符串,将每个两位一组的字符转换为其对应的十进制数值,然后累加到结果上。注意,此代码假设输入的字符串是有效的、正确的十六进制。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)