0

I am a beginner at C programming. I researched how to get a solution to my problem but I didn't find an answer so I asked here. My problem is:

I want to convert a hex array to a string. for example:

it is my input hex: uint8_t hex_in[4]={0x10,0x01,0x00,0x11};

and I want to string output like that: "10010011"

I tried some solutions but it gives me as "101011" as getting rid of zeros.

How can I obtain an 8-digit string?

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

int main(){

    char dene[2];
    uint8_t hex_in[4]={0x10,0x01,0x00,0x11};
    //sprintf(dene, "%x%*x%x%x", dev[0],dev[1],2,dev[2],dev[3]);
    //sprintf(dene, "%02x",hex_in[1]);
    printf("dene %s\n",dene);
}
5
  • 2
    Can you show the code? Commented Jun 17, 2021 at 6:22
  • 1
    Tell sprintf the width and the padding: for example sprintf(str, "%02X", hex_in[0]); which will generate 2 digits with '0' padding. Commented Jun 17, 2021 at 6:27
  • We can't help you finding the problems in your code unless you post it. Commented Jun 17, 2021 at 6:56
  • @WeatherVane I tried that but it didnt work Commented Jun 17, 2021 at 7:17
  • char dene[2]; ==> char dene[9]; Then sprintf(dene, "%02X%02X%02X", hex_in[0], hex_in[1], hex_in[2], hex_in[3]); Commented Jun 17, 2021 at 7:31

1 Answer 1

1

In order to store the output in a string, the string must be large enough. In this case holding 8 digits + the null terminator. Not 2 = 1 digit + the null terminator.

Then you can print each number with %02x or %02X to get 2 digits. Lower-case x gives lower case abcdef, upper-case X gives ABCDEF - otherwise they are equivalent.

Corrected code:

#include <stdio.h>
#include <stdint.h>

int main(void)
{
  char str[9];
  uint8_t hex_in[4]={0x10,0x01,0x00,0x11};
  sprintf(str,"%02x%02x%02x%02x\n", hex_in[0],hex_in[1],hex_in[2],hex_in[3]);
  puts(str);
}

Though pedantically, you should always print uint8_t and other types from stdint.h using the PRIx8 etc specifiers from inttypes.h:

#include <inttypes.h>


sprintf(str,"%02"PRIx8"%02"PRIx8"%02"PRIx8"%02"PRIx8"\n", 
        hex_in[0],hex_in[1],hex_in[2],hex_in[3]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.