简介本文介绍一个C++代码片段:C++十六进制输出为字符串,感兴趣的朋友可以参考一下。

代码

#include <string>
#include <iostream>
using namespace std;

typedef unsigned char BYTE;
string HexToString_Blank(const BYTE *pBuffer, size_t iBytes)
{
	string result;

	for (size_t i = 0; i < iBytes; i++)
	{
		BYTE c;

		BYTE b = pBuffer[i] >> 4;

		if (9 >= b)
		{
			c = b + '0';
		}
		else
		{
			c = (b - 10) + 'A';
		}

		result += (TCHAR)c;

		b = pBuffer[i] & 0x0f;

		if (9 >= b)
		{
			c = b + '0';
		}
		else
		{
			c = (b - 10) + 'A';
		}

		result += (TCHAR)c;
		result += " ";
	}

	return result;
}

使用示例


int main(int argc, char const *argv[])
{
	char chMsg[] = "C++实战网(www.cppszw.com)";
	int iMsgLen = sizeof(chMsg);
	BYTE* pBData = new BYTE[iMsgLen];
	for (int i = 0; i < iMsgLen; ++i)
	{
		pBData[i] = chMsg[i];
	}
	cout << HexToString_Blank(pBData, iMsgLen) << endl;
    delete[] pBData;
	return 0;
}

输出:

C++代码片段,字符串相关,C++十六进制输出为字符串

更多为你推荐