下面代码分别给出了三种将二进制字节字符转换为ASCII的方法
/** * @brief 该函数实现了将二进制字节数据转换为可打印ASCII码字符串 * @param[in] pSrc 源数据指针 * @param[in] nSrcLength 源数据长度 * @param[out] pDst 目标字符串指针 * @return 目标字符串长度 * @author wlq_729@163.com * http://blog.csdn.net/rabbit729 * @version 1.0 * @date 2009-02-25 */ #include <assert.h> #include <iostream> using namespace std; int BinaryBytes2String1(const unsigned char* pSrc, unsigned int nSrcLength, char* pDst) { if ( pSrc == 0 || pDst == 0 ) return 0; char* p = pDst; for ( unsigned i = 0; i < nSrcLength; i++ ) { *p = (pSrc[i] >> 4) & 0x0f; *p += *p < 10 ? 0x30 : (0x61 - 10); p++; *p = pSrc[i] & 0x0f; *p += *p < 10 ? 0x30 : (0x61 - 10); p++; } *p = '/0'; return nSrcLength * 2; } int BinaryBytes2String2(const unsigned char* pSrc, unsigned int nSrcLength, char* pDst ) { if ( pSrc == 0 || pDst == 0 ) return 0; const char tab[]="0123456789abcdef"; for(int i=0; i<nSrcLength; i++) { *pDst++ = tab[*pSrc >> 4]; *pDst++ = tab[*pSrc & 0x0f]; pSrc++; } *pDst = '/0'; return nSrcLength * 2; } int BinaryBytes2String3(const unsigned char* pSrc, int nSrcLength, char* pDst) { if ( pSrc == 0 || pDst == 0 ) return 0; for (int i = 0; i < nSrcLength; i++) { sprintf(pDst, "%02x", *pSrc); pDst++; pDst++; pSrc++; } *pDst = '/0'; return nSrcLength * 2; } void main(void) { unsigned char test[3] = {0x23, 0xa4, 0xB7}; char result[7]; memset(result, 0, 7); BinaryBytes2String1(test, 3, result); cout<<result<<endl; BinaryBytes2String2(test, 3, result); cout<<result<<endl; BinaryBytes2String3(test, 3, result); cout<<result<<endl; }
输出结果为:
23a4b723a4b723a4b7请按任意键继续. . .