Solved

# splitting digit hex codes into 2 chars

Posted on 2004-09-21
239 Views
Last Modified: 2010-04-15
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
Question by:dublinsoft
8 Comments

LVL 5

Accepted Solution

tzxie2000 earned 43 total points
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

LVL 86

Expert Comment

What about

int x1=0x01;

printf("%2.2x", x1);

?
0

LVL 86

Assisted Solution

jkr earned 41 total points
Or

char ac[2]
int x1=0x01;

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

?

0

LVL 55

Expert Comment

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

Expert Comment

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

LVL 55

Assisted Solution

Jaime Olivares earned 41 total points
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

## Join & Write a Comment Already a member? Login.

### Suggested Solutions

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.

#### 772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

#### Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!