mehmet
mehmet

Reputation: 1

input hex to string output in C

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);
}

Upvotes: 0

Views: 759

Answers (1)

Lundin
Lundin

Reputation: 213832

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]);

Upvotes: 1

Related Questions