C++实现字节数组与16进制字符串互转,字符串转16进制字符串

  1. 无符号字节数组转16进制字符串
std::string bytesToHexString(const BYTE* bytes,const int length) 
{
	if (bytes == NULL) {
		return "";
	}
	std::string buff;
	const int len = length;
	for (int j = 0; j < len; j++) {
		/*if ((bytes[j] & 0xff) < 16) {
			buff.append("0");
		}*/
		int high = bytes[j]/16, low = bytes[j]%16;
		buff += (high<10) ? ('0' + high) : ('a' + high - 10);
		buff += (low<10) ? ('0' + low) : ('a' + low - 10);
	}
	return buff;
}
  1. 16进制字符串 转无符号字节数组
void hexToBytes(const std::string& hex,BYTE* bytes) 
{
	int bytelen = hex.length() / 2;
	std::string strByte;
	unsigned int n;
	for (int i = 0; i < bytelen; i++) 
	{
		strByte = hex.substr(i * 2, 2);
		sscanf(strByte.c_str(),"%x",&n);
		bytes[i] = n;
	}
}
  1. 字符串转16进制字符串
/*
* 将字符串编码成16进制数字,适用于所有字符(包括中文)
*/
std::string encodeHexString(const std::string& str) {
	// 根据默认编码获取字节数组
	std::string hexString = "0123456789abcdef";
	string sb;
	// 将字节数组中每个字节拆解成2位16进制整数
	for (int i = 0; i < str.length(); i++) {
		sb += hexString.at((str[i] & 0xf0) >> 4);
		sb += hexString.at((str[i] & 0x0f) >> 0);
	}
	return sb;
}
  1. 16进制字符串转字符串
std::string hexStringToString(const std::string& hexStr) 
{
	std::string ret;
	std::string hexString = "0123456789abcdef";
	// 将每2位16进制整数组装成一个字节
	for (int i = 0; i < hexStr.length(); i += 2)
		ret	+= BYTE(hexString.find(hexStr.at(i)) << 4 | hexString.find(hexStr.at(i + 1)));
	return ret;
}

你可能感兴趣的:(C/C++)