character hexadeximal

Reply

Join Date: Apr 2008
Posts: 29
Reputation: savinki is an unknown quantity at this point 
Solved Threads: 0
savinki savinki is offline Offline
Light Poster

character hexadeximal

 
0
  #1
Apr 21st, 2008
I want to convert a character to hexadecimal value.
and that value should be a unsigned char value.
e.g.
unsigned char a[16] = {0x00,0x44,...};

this is the code segment i wrote.
but its not working properly.
unsigned char a1= 'D';
unsigned char a[4] ;
unsigned char temp[16];
sprintf((char *)a,"0x%02X",a1);
cout<<a;
unsigned char *b=a;
cout<<b;
temp[0] = b;

can anyone help me to overcome from this issue
Reply With Quote Quick reply to this message  
Join Date: Sep 2004
Posts: 8,313
Reputation: Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute 
Solved Threads: 825
Team Colleague
Narue's Avatar
Narue Narue is offline Offline
Code Goddess

Re: character hexadeximal

 
1
  #2
Apr 21st, 2008
'D' isn't likely to have the value 13. You need to convert the character to a hexadecimal digit value:
  1. #include <cctype>
  2.  
  3. // Return [0,15] on success, -1 on failure
  4. int hex_value ( unsigned char c )
  5. {
  6. if ( std::isxdigit ( c ) ) {
  7. // Assume 'A' - 'F' have consecutive values
  8. return std::isdigit ( c ) ? c - '0' : toupper ( c ) - 'A' + 10;
  9. }
  10.  
  11. return -1;
  12. }
  1. sprintf ( a, "0x%02X", hex_value ( a1 ) );
By the way, you store the hexadecimal values as unsigned char, but the string representation should be char. There's no type mismatch here as you're using sprintf to convert the values to a character representation.
In case you were wondering, yes, I do hate you.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Other Threads in the C++ Forum


Views: 443 | Replies: 1
Thread Tools Search this Thread



Tag cloud for C++
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2010 DaniWeb® LLC