I've had some trouble with binary-to-(printable)hexa conversions. I've reached a functional (for my system) way of writing the code, but I need to know if it is portable on all systems (OS & hardware).
So this is my function (trying to construct a UUID from a piece of binary text):
int extractInfo( unsigned char * text )
{
char h[3];
int i;
this->str.append( "urn:uuid:" );
for( i = 56; i < 72; i++ )
{
ret = snprintf( h, 3, "%02x", text[i] );
if( ret != 2 )
return 1;
this->str.append( h );
if( i == 59 || i == 61 || i == 63 || i == 65 )
this->str.append( "-" );
}
return 0;
}
I understood that because of the sign extension my values are not printed well if I use char instead of unsigned char (C++ read binary file and convert to hex). Accepted and modified respectively.
But I've encountered more variants of doing this: Conversion from binary file to hex in C, and I am really lost. In unwind's piece of code:
sprintf(hex, "%02x", (unsigned int) buffer[0] & 0xff);
I did not understood why, although the array is unsigned char (as defined in the original posted code, by the one who asked the question), a cast to an unsigned int is needed, and also a bitwise AND on the byte to be converted...
So, as I did not understood very well the sign-extension thing, can you tell me at least if the piece of code I wrote will work on all systems?