简体   繁体   中英

C - converting hex to string

Following on an old question Converting hex to string in C?

The approved answer suggests to use sprintf to convert each hex to string.

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 .

2) What am i doing wrong here?

#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

3) Combining both the both questions, i want my result string to be 4aabab0a40

TIA

Your code has several problems.

First unsigned char temp[10]; should be unsigned char temp[11]; to contain a string terminator.

Next is the format spec "%x" should be "%02x" so each value is 2 digits.

Then temp + i should be temp + i*2 so each pair of digits is written in the right place.

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

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.

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