c - 在 C 中将 HEX 值转换为 DECimal 值
问题描述
我已经从 SO 中尝试了很多想法。当我在这里对其进行测试时,其中一个有效(HEX 31 的输出为 DEC 49)。但是,当我在我的应用程序中实现它时,它并没有产生相同的结果。(输出是 31 又是 31)。
这个想法是使用一个字符串值(充满十六进制对);一个例子; 313030311b5b324a1b5b324a534f495f303032371b
我需要将每个整数对(HEX)转换为等价的十进制值。例如
HEX => DEC
31 => 49
30 => 48
然后,我将使用 UART 逐个值发送 DEC 值。
我测试行为的代码在下面和这里;但是,它不一定是那个代码,只要它能完成工作,我愿意接受所有建议。
#include <stdio.h>
int isHexaDigit(char p) {
return (( '0' <= p && p <= '9' ) || ( 'A' <= p && p <= 'F'));
}
int main(int argc, char** argv)
{
char * str = "31";
char t[]="31";
char* p = t;
char val[3]; // 2 hexa digit
val[2] = 0; //and the final \0 for a string
int number;
while (isHexaDigit(*p) && isHexaDigit(*(p+1))) {
val[0] = *p;
val[1] = *(p+1);
sscanf(val,"%X", &number); // <---- Read hexa string into number
printf("\nNum=%i",number); // <---- Display number to decimal.
p++;
//p++;
if (!*p) break;
p++;
}
return 0;
}
编辑 我最小化了代码。奇数字符串暂时被忽略。代码逐字节发送数据。在终端应用程序中,我将值作为 HEX,例如 HEX 31 而不是 DEC 49。它们实际上是相同的。但是,我使用的设备需要 DEC 49 版本的值(即 ASCII = 1)
任何指针高度赞赏。
解决方案
您可以使用strtol
函数将十六进制字符串转换为二进制,然后在一行中将其转换为十进制字符串:
snprintf(str_dec, 4, "%ld", strtol(str_hex, NULL, 16));
您的代码变为:
#include <stdio.h>
#include <stdlib.h>
int isHexaDigit(char p) {
return (( '0' <= p && p <= '9' ) || ( 'A' <= p && p <= 'F'));
}
int main(int argc, char** argv)
{
char * str = "31";
char t[]="31";
char* p = t;
char str_hex[3] = {0,};
char str_dec[4] = {0,};
while (isHexaDigit(*p) && isHexaDigit(*(p+1))) {
str_hex[0] = *p;
str_hex[1] = *(p+1);
/* Convert hex string to decimal string */
snprintf(str_dec, 4, "%ld", strtol(str_hex, NULL, 16));
printf("str_dec = %s\n", str_dec);
/* Send the decimal string over UART1 */
if (str_dec[0]) UART1_Write(str_dec[0]);
if (str_dec[1]) UART1_Write(str_dec[1]);
if (str_dec[2]) UART1_Write(str_dec[2]);
/* Reset str_dec variable */
str_dec[0] = 0;
str_dec[1] = 0;
str_dec[2] = 0;
p++;
if (!*p) break;
p++;
}
return 0;
}
推荐阅读
- javascript - MapBox 反向地理编码
- git - eslint 和 vue 的预提交钩子
- javascript - 有没有办法将对象属性作为单个参数动态传递?
- java - 处理损坏的 install4j 安装程序
- r - 反应函数问题,尝试更改正在导入的数据集列的类型(R Shiny)
- java - Spring Mongo 是否默认公开集合的端点?
- css - Bootstrap 响应式导航栏切换按钮不起作用
- java - Gradle 找不到主类原因:java.lang.ClassNotFoundException: C:\data\workspace\dev\tools\java_security for Java 11
- python-3.x - 按记录搜索字典
- c# - 在 asp.net core 3.1 中使用最新的 GraphQL 库时无法解析 IDependencyResolver 和 ResolveFieldContext