简体   繁体   English

C - 将十六进制转换为字符串

[英]C - converting hex to string

Following on an old question Converting hex to string in C?继续一个老问题将十六进制转换为 C 中的字符串?

The approved answer suggests to use sprintf to convert each hex to string.批准的答案建议使用 sprintf 将每个十六进制转换为字符串。

I have two question on this -我对此有两个问题-

1) When i have a hex like 0a i want my string to have 0a too, but following the above solution the result will have a . 1)当我有一个像0a这样的十六进制时,我希望我的字符串也有0a ,但是按照上述解决方案,结果将有a .

2) What am i doing wrong here? 2)我在这里做错了什么?

#include <stdio.h>

int main(void)
{
    unsigned char readingreg[10];
    readingreg[0] = 0x4a;
    readingreg[1] = 0xab;
    readingreg[2] = 0xab;
    readingreg[3] = 0x0a;
    readingreg[4] = 0x40;
    unsigned char temp[10];
    int i = 0;

    while (i < 5)
    {
        sprintf(temp + i, "%x", readingreg[i]);
        i++;
    }
    printf("String: %s\n", temp);
    return 0;
}

The o/p seems to - String: 4aaa40 o/p 似乎 - String: 4aaa40

3) Combining both the both questions, i want my result string to be 4aabab0a40 3)结合这两个问题,我希望我的结果字符串是4aabab0a40

TIA TIA

Your code has several problems.您的代码有几个问题。

First unsigned char temp[10];第一个unsigned char temp[10]; should be unsigned char temp[11];应该是unsigned char temp[11]; to contain a string terminator.包含一个字符串终止符。

Next is the format spec "%x" should be "%02x" so each value is 2 digits.接下来是格式规范"%x"应该是"%02x"所以每个值都是 2 位数字。

Then temp + i should be temp + i*2 so each pair of digits is written in the right place.那么temp + i应该是temp + i*2所以每对数字都写在正确的地方。

Correcting those mistakes:纠正这些错误:

#include <stdio.h>

int main(void)
{
    unsigned char readingreg[10];
    readingreg[0] = 0x4a;
    readingreg[1] = 0xab;
    readingreg[2] = 0xab;
    readingreg[3] = 0x0a;
    readingreg[4] = 0x40;
    unsigned char temp[11];
    int i = 0;

    while (i < 5)
    {
        sprintf(temp + i*2, "%02x", readingreg[i]);
        i++;
    }
    printf("String: %s\n", temp);
    return 0;
}

Program output is now the required程序输出现在是必需的

String: 4aabab0a40

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

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