0

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

Edited by mike_2000_17: Fixed formatting

2
Contributors
1
Reply
2
Views
9 Years
Discussion Span
Last Post by Narue
0

'D' isn't likely to have the value 13. You need to convert the character to a hexadecimal digit value:

#include <cctype>

// Return [0,15] on success, -1 on failure
int hex_value ( unsigned char c )
{
  if ( std::isxdigit ( c ) ) {
    // Assume 'A' - 'F' have consecutive values
    return std::isdigit ( c ) ? c - '0' : toupper ( c ) - 'A' + 10;
  }

  return -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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.