Go Premium for a chance to win a PS4. Enter to Win

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

How to printf("%02X",CBuf) to FF but not to FFFFFFFF

char CBuf;

CBuf=0xFE;
 printf("%02X",CBuf);

I wish the result is FE, but it is FFFFFFFE.
Who can help me this? thanks!
0
wpy
Asked:
wpy
1 Solution
 
ozoCommented:
unsigned char CBuf;
0
 
wpyAuthor Commented:
thanks !! it work well!
0
 
RONSLOWCommented:
the problem is that the %x format is expecting an int.  You have put in a (signed) character with a negative value so the sign bit gets extended (ie. you end up with a negative int).

Either change CBuf to and unsigned char (as suggested) OR
cast it to unsigned char in the printf
eg.

print ("%02x",unsigned char(CBuf));

The best solution depends on what you subsequently want to do with CBuf.  If you are going to put in into a string, then you probably want to keep it a plain char (not make it unsigned) and just cast when you want to see the HEX value.

0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

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