#include<stdio.h>
#include<stdlib.h>
unsigned char *hexstr_to_hex( int length, const char *hexstr);
int main( int argc, char *argv[])
{
unsigned char buffer[20];
hexstr_to_hex(4, "1234" );
//printf( "buffer is %s",buffer );
return 0;
}
/*字符长度缩短一半,16进制构成的数组转化成16进数,比如“1234”字符串要转化成12 34*/
unsigned char *hexstr_to_hex(int length, const char *hexstr)
{
int j, k;
unsigned char* buff;
unsigned char* new_buff;
int bytes_length;
k = 0;//as counter ,when odd begin trans
bytes_length = (length % 2) + (length / 2);
buff =(unsigned char*)malloc(length);
printf("hex str %s\n", hexstr);
memcpy(buff, hexstr, length);
printf("buff str %s\n", buff);
printf( "buffer length is %d\n" , bytes_length );
new_buff = malloc(bytes_length);
memset(new_buff, 0, bytes_length);
for(j = length - 1; j >= 0; j--)
{
printf( "------------------j = %d\n" ,j);
if((k % 2) == 0)
{
printf( "+++++++++++++++j = %d, low 4 bit\n" ,j);
if(buff[j] >= '0' && buff[j] <= '9')
{ printf( "buff[%d]=%d\n", j,buff[j] );
new_buff[j/2] = ((buff[j] - 48) & 0x0F);
printf( "new_buff[%d] = %d\n", j/2, new_buff[j/2] );
} else if(buff[j] >= 'a' && buff[j] <= 'f')
{
new_buff[j/2] = ((buff[j] - 97 + 10) & 0x0F);
} else if(buff[j] >= 'A' && buff[j] <= 'F')
{
new_buff[j/2] = ((buff[j] - 65 + 10) & 0x0F);
} else
{
printf("must be hex decime\n");
free(buff);
free(new_buff);
return NULL;
}
if( j > 0)
{
printf( "+++++++++++++++use j-1 = %d, high 4 bit\n" ,j-1);
if(buff[j - 1] >= '0' && buff[j - 1] <= '9')
{
new_buff[j/2] |= (((buff[j-1] - 48) << 4) & 0xF0);
} else if(buff[j - 1] >= 'a' && buff[j - 1] <= 'f')
{
new_buff[j/2] |= (((buff[j-1] - 97 + 10) << 4) & 0xF0);
} else if(buff[j - 1] >= 'A' && buff[j - 1] <= 'F')
{
new_buff[j/2] |= (((buff[j-1] - 65 + 10) << 4) & 0xF0);
} else
{
printf("must be hex decime\n");
free(buff);
free(new_buff);
return NULL;
}
}
printf("new_buff[%d] = %d\n", j/2, new_buff[j/2] );
}
//when k is even number , continue:good job
if((k % 2) == 1)
{
k++;
continue;
}
k++;
}
printf( "--------------old buffer is :\n" );
printf("%s\n", buff);
printf( "--------------new buffer is :\n" );
for(k = 0; k < bytes_length; k++)
{
printf("%x\n", new_buff[k]);
}
|