Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download
Views: 549
1
#include <stdio.h>
2
#include <stdlib.h>
3
#include <string.h>
4
#include <ctype.h>
5
#include "hex.h"
6
7
/**
8
* Check to see if the input starts with "0x"; if it does, return the decoded
9
* bytes of the following data (presumed to be hex coded). If not, just return
10
* the contents. This routine allocates memory, so has to be free'd.
11
*/
12
int hex_decode( const unsigned char *input, unsigned char **decoded )
13
{
14
int i;
15
int len;
16
17
if ( strncmp( "0x", input, 2 ) )
18
{
19
len = strlen( input ) + 1;
20
*decoded = malloc( len );
21
strcpy( *decoded, input );
22
len--;
23
}
24
else
25
{
26
len = ( strlen( input ) >> 1 ) - 1;
27
*decoded = malloc( len );
28
for ( i = 2; i < strlen( input ); i += 2 )
29
{
30
(*decoded)[ ( ( i / 2 ) - 1 ) ] =
31
( ( ( input[ i ] <= '9' ) ? input[ i ] - '0' :
32
( ( tolower( input[ i ] ) ) - 'a' + 10 ) ) << 4 ) |
33
( ( input[ i + 1 ] <= '9' ) ? input[ i + 1 ] - '0' :
34
( ( tolower( input[ i + 1 ] ) ) - 'a' + 10 ) );
35
}
36
}
37
38
return len;
39
}
40
41
void show_hex( const unsigned char *array, int length )
42
{
43
while ( length-- )
44
{
45
printf( "%.02x", *array++ );
46
}
47
printf( "\n" );
48
}
49
50