C 字符串与二进制数组转换

#include "stdafx.h" #include "stdio.h" #include "string.h" int Bytes2String(unsigned char *pSrc, int nSrcLen, unsigned char *pDst, int nDstMaxLen) { if (pDst != NULL) { *pDst = 0; } if (pSrc == NULL || nSrcLen <= 0 || pDst == NULL || nDstMaxLen <= nSrcLen*2) { return 0; } //0x0-0xf的字符查找表 const char szTable[] = "0123456789ABCDEF"; for(int i=0; i<nSrcLen; i++) { //输出低4位 *pDst++ = szTable[pSrc[i] >> 4]; // 输出高4位 *pDst++ = szTable[pSrc[i] & 0x0f]; } // 输出字符串加个结束符 *pDst = '/0'; //返回目标字符串长度 return nSrcLen * 2; } int String2Bytes(unsigned char* szSrc, unsigned char* pDst, int nDstMaxLen) { if(szSrc == NULL) { return 0; } int iLen = strlen((char *)szSrc); if (iLen <= 0 || iLen%2 != 0 || pDst == NULL || nDstMaxLen < iLen/2) { return 0; } iLen /= 2; strupr((char *)szSrc); for (int i=0; i<iLen; i++) { int iVal = 0; unsigned char *pSrcTemp = szSrc + i*2; sscanf((char *)pSrcTemp, "%02x", &iVal); pDst[i] = (unsigned char)iVal; } return iLen; } int main(int argc, char* argv[]) { unsigned char s1[128] = "2f17211111222233334444"; unsigned char s2[128] = {0}; unsigned char s3[128] = {0}; int l = String2Bytes(s1, s2, 128); Bytes2String(s2, l, s3, 128); return 0; }

你可能感兴趣的:(c,String,null,include)