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

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

/* hex42bin.c
 * Heiher 
 */

#include 
#include 
#include 

int inline hex_to_bin(char hex, char * buf, int bit)
{
	if(!buf || ((0>bit)&&(3=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=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

Over!

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

Leave a Reply

Your email address will not be published.