sscanf is really the best option here, of course - this is just an example of doing it 'by hand':
Code:
int
hex_char_to_binary( char ch, char* ret )
{
ch = tolower( ch );
if( isdigit( ch ) )
*ret = ch - '0';
else if( ch >= 'a' && ch <= 'f' )
*ret = ( ch - 'a' ) + 10;
else
return *ret = 0;
return 1;
}
char*
hex_to_binary_copy( const char* str, char* ret )
{
char
* cpy = ret,
low,
high;
if( strlen( str ) % 2 )
{
*ret = 0;
return 0;
}
for( const char* ptr = str; *ptr; ptr += 2 )
{
if
(
!hex_char_to_binary( *ptr, &high )
||
!hex_char_to_binary( *( ptr + 1 ), &low )
)
{
*ret = 0;
return 0;
}
*cpy++ = low | ( high << 4 );
}
*cpy = 0;
return ret;
}
[edit]
Or perhaps better yet:
[/edit]
Code:
int
hex_to_binary( const char* str, void* buf, int* siz )
{
char
* cpy = ( char* )buf,
low,
high;
const char
* ptr = str;
int
unused,
len = strlen( str ),
half = len / 2,
odd = len % 2;
if( siz == 0 )
siz = &unused;
if( odd )
{
/*
a bit of a hack...
*/
--ptr;
++half;
high = 0;
goto skip;
}
for( ; *ptr; ptr += 2 )
{
if( !hex_char_to_binary( *ptr, &high ) )
return *siz = 0;
skip:
if( !hex_char_to_binary( *( ptr + 1 ), &low ) )
return *siz = 0;
*cpy++ = low | ( high << 4 );
}
return *siz = half;
}