//
// DecToHex.cpp
//
// Sample :
// unsigned char s1[8]="12345678" Cast to unsigned char s2[4]={0x12,0x34,0x56,0x78}
// unsigned char s1[8]="ABCDEF78" Cast to unsigned char s2[4]={0xAB,0xCD,0xEF,0x78}
// unsigned char s1[8]="abcdef78" Cast to unsigned char s2[4]={0xab,0xcd,0xef,0x78}
// ASCII code value
// a - z : ( hex value ) 61 -- 7A
// A - Z : ( hex value ) 41 -- 5A
// 0 - 9 : { hex value } 30 -- 39
// { '0'- '9' } - '0' = { 0 -- 9 }
// { 'a - 'f' } - '0' = { 31 -- 36 }
// { 'A'- 'Z' } - '0' = { 11 -- 16 }
#include <iostream>
unsigned char* StrToHexArray( unsigned char* strSrc, unsigned char* strDest );
int main()
{
unsigned char s1[] = "12345678";
unsigned char s2[] = "ABCDEF78";
unsigned char s3[] = "abcdef78";
std::cout << s1 << " size is " << sizeof( s1 ) << std::endl;
std::cout << s2 << " size is " << sizeof( s2 ) << std::endl;
std::cout << s3 << " size is " << sizeof( s3 ) << std::endl;
unsigned char* s4 = new unsigned char[ 4 ];
StrToHexArray( s1, s4 );
for ( int i = 0; i < 4; i++ )
printf( "0x%X ", s4[ i ] );
std::cout << std::endl;
StrToHexArray( s2, s4 );
for ( i = 0; i < 4; i++ )
printf( "0x%X ", s4[ i ] );
std::cout << std::endl;
StrToHexArray( s3, s4 );
for ( i = 0; i < 4; i++ )
printf( "0x%X ", s4[ i ] );
std::cout << std::endl;
delete s4;
return 0;
}
unsigned char* StrToHexArray( unsigned char* strSrc, unsigned char* strDest )
{
if ( strSrc == NULL || strDest == NULL )
return NULL;
int nDone = 0;
unsigned char* tmp = strSrc;
unsigned char* tmp2 = strDest;
while ( *strSrc )
{
nDone++;
unsigned char value = *strSrc - '0';
if ( value <= 9 )
NULL;
else if ( value >= 0x31 && value <= 0x36 )
value -= 0x27;
else if ( value >= 0x11 && value <= 0x16 )
value -= 0x07;
if ( ( nDone % 2 ) == 1 )
{
value <<= 4;
*strDest = value;
}
if ( ( nDone % 2 ) == 0 )
{
*strDest += value;
strDest++;
value = 0;
}
strSrc++;
}
strSrc = tmp;
strDest = tmp2;
return tmp;
}