hex_to_ascii

总是在不经意间需要使用的函数有很多.. 字符串转换方面是个大头.. 刚好这边有两个非常好用的函数, 收集起来..

char *hex_to_ascii(char *dest, const char src[], int size)
{
	char *ret = dest;
	int i;

	for (i = 0; i < size; i++)
	{
		*dest++ = "0123456789ABCDEF"[(unsigned char)src[i] >> 4];
		*dest++ = "0123456789ABCDEF"[src[i] & 0xf];
		*dest++ = ' ';
	}
	*dest = 0;

	return ret;
}

char *ascii_to_string(char *dest, const char src[], int size)
{
#define char_to_hex(ch) (('0' <= (ch) && (ch) <= '9') ? ((ch) & 0xf) : (((ch) & 0xf) + 9))
	char *ret = dest;
	int i = 0;
	while (i < size)
	{
		char ch1 = src[i];
		char ch2 = src[i + 1];
		*dest++ = ((char_to_hex(ch1) << 4) | char_to_hex(ch2));
		i += 2;
	}

	return ret;
}

发表评论

发表评论前,请选对水果【Apple=苹果、Banana=香蕉、Pineapple=菠萝、Grapes=葡萄】Pineapple