十六进制和二进制字符串互转例程

模拟人工运算方式实现的十六进制和二进制字符串互转例程,效率应该还行吧。

/* hex42bin.c
 * Heiher <admin@heiher.info>
 */
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int inline hex_to_bin(char hex, char * buf, int bit)
{
	if(!buf || ((0>bit)&&(3<bit)))
	{
		return -1;
	}
 
	if(hex & (0x1 << bit))
	{
		buf[3-bit] = '1';
	}
 
	return 0;
}
 
int hex2bin(char hex, char * buf)
{
	char c = 0, * p = NULL;
	int i = 0;
 
	if(!buf)
	{
		return -1;
	}
 
	if(('0'<=hex) && ('9'>=hex))
	{
		c = hex - 0x30;
	}
	else if((('A'<=hex)&&('F'>=hex)) ||
				(('a'<=hex)&&('f'>=hex)))
	{
		c = hex - 0x37;
	}
	else
	{
		return -1;
	}
 
 
	for(i=0; i<4; i++)
	{
		if(-1 == hex_to_bin(c, buf, i))
		{
			return -1;
		}
	}
 
	return 0;
}
 
int inline  bin_to_hex(const char * hex, char * buf, int bit)
{
	if(!hex || !buf || ((0>bit)||(3<bit)))
	{
		return -1;
	}
 
	if('1' == hex[3-bit])
	{
		buf[0] |= (0x1 << bit);
	}
 
	return 0;
}
 
int bin2hex(const char * hex, char * buf)
{
	int i = 0;
 
	if(!hex || !buf)
	{
		return -1;
	}
 
	for(i=0; i<4; i++)
	{
		if(-1 == bin_to_hex(hex, buf, i))
		{
			return -1;
		}
	}
	if((0<=buf[0]) && (9>=buf[0]))
	{
		buf[0] += 0x30;
	}
	else if((0xA<=buf[0]) && (0xF>=buf[0]))
	{
		buf[0] += 0x37;
	}
	else
	{
		return -1;
	}
 
	return 0;
}
 
int main(int argc, char * argv[])
{
	int i = 0, len = 0;
	char hex_str[] = "AaBbCcDdEeFf0123456789";
	char * bin_str = NULL;
 
	len = strlen(hex_str);
	bin_str = malloc(len*4+1);
 
	/* hex to bin */
	memset(bin_str, '0', len*4+1);
	for(i=0; i<len; i++)
	{
		if(-1 == hex2bin(hex_str[i], bin_str+i*4))
		{
			goto error;
		}
	}
	printf("Bin String: %s\n", bin_str);
 
	/* bin to hex */
	memset(hex_str, 0, len);
	for(i=0; i<len; i++)
	{
		hex_str[i] = 0;
		if(-1 == bin2hex(bin_str+4*i, hex_str+i))
		{
			goto error;
		}
	}
	printf("Hex String: %s\n", hex_str);
 
	return 0;
 
error:
	printf("Error!\n");
 
	return 0;
}

Over!

4 thoughts on “十六进制和二进制字符串互转例程”

Leave a Reply

Your email address will not be published. Required fields are marked *