Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 252
• Last Modified:

# splitting digit hex codes into 2 chars

Hi i am trying to convert the two digit hex value of unprintable chars into two seperate chars, then i can print them as part of a normal C-String

I Have tried

char char1, char2;
int x1 0x01;

char1 = (x1/16)+'0';
char2 = (x1%16)+'0';

printf("%c %c", char1, char2);

Ok where am I going wrong. Please help

0
dublinsoft
Asked:
3 Solutions

Commented:
as hex is 0-9,A-F

so  if the high part of x1 is bigger then 9 like int x1 0xA1 you will get error output

so you should check it
for example

if(x1/16<10)
char1 = (x1/16)+'0';
else
char1 = (x1/16-10)+'A';
0

Commented:
What about

int x1=0x01;

printf("%2.2x", x1);

?
0

Commented:
Or

char ac[2]
int x1=0x01;

snprintf(ac,2,"%2.2x", x1);

?

0

Software ArchitectCommented:
you can use standard itoa() function:

char hex[3];
int x1 = 0x01;  /* there is a missing = sign in your example */

itoa (x1, hex, 16);

/* now your digits are hex[0] and hex[1] */
printf("%c %c", hex[0], hex[1]);

0

Commented:

void main()
{
int n=0xAB;
char sol[2];
sprintf(sol,"%x",n);
printf("%c and %c are the 2 digits",sol[0],sol[1]);
}

PS> Hope this helps

Regards
Aakash
0

Software ArchitectCommented:
Just noticed mine and aakash won't work with 1 digit values. Must be:

void main()
{
int n=0x1;
char sol[3];                   // Buffer must have 3 bytes, for trailing null character
sprintf(sol,"%02X",n);    // Notice the %02X format, will ensure a leading 0 if number has 1 digit only.
printf("%c and %c are the 2 digits",sol[0],sol[1]);
}
0

## Featured Post

Tackle projects and never again get stuck behind a technical roadblock.