-2

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

pa1
  • 778
  • 3
  • 11
  • 26

1 Answers1

3

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
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
  • Are arrays to be used as make-believe strings not supposed to be the compiler defaults' `char` type? – Jongware Dec 25 '17 at 23:38
  • @usr2564301 the compiler's default `char` type may well be unsigned. Strings in C are "make-believe" if you like, C has no string type. They are arrays with a nul terminator. – Weather Vane Dec 25 '17 at 23:41
  • It is of no consequence for OP's code or your answer, but still :) The usual prototypes for string functions mention just `char`, that is, they *do* adhere to the compiler default. That's why I mentioned it, as a warning for OP – a manual override to *either* `signed` or `unsigned` may trigger warnings. – Jongware Dec 25 '17 at 23:44