请问如何将一个字符串两两解析成十六进制值存入一个字节中
如字符串“4A9000”
请问如何将它转换成十六进制数:0x4A, 0x90, 0x00,从而使得这三个能分别存入字节数组中呢?
即是 unsigned char ch[3];
ch[0] = 0x4A;
ch[1] = 0x90;
ch[2] = 0x00;
[解决办法]
int __stdcall CrnHexToByte(LPCSTR lpInBuf, LPBYTE lpOutBuf){ size_t uInLen; uInLen = strlen(lpInBuf); int nResult = 0; if (uInLen < 2) return nResult; BYTE c; for (size_t i = 0; i < uInLen; i += 2) { // 输出高4位 c = lpInBuf[i]; if (c >= '0' && c <= '9') lpOutBuf[nResult] = (c - '0') << 4; else if (c >= 'A' && c <= 'F') lpOutBuf[nResult] = (c - 'A' + 10) << 4; // 输出低4位 c = lpInBuf[i + 1]; if (c >= '0' && c <= '9') lpOutBuf[nResult++] |= (c - '0'); else if (c >= 'A' && c <= 'F') lpOutBuf[nResult++] |= (c - 'A' + 10); } return nResult;}void __fastcall TForm1::Button1Click(TObject *Sender){ char sz[] = "4A9000"; unsigned char bt[3]; int n = CrnHexToByte(sz, bt); Caption = n;}
[解决办法]
大概是这样的
int ReadHexStr(const char *szSrc, unsigned char *pucOutput) { const char *pch = szSrc; int nCount; int snChar = 0; while ( *szSrc != 0 ) { unsigned char ucValue; switch ( *szSrc ) { case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' : ucValue = *szSrc - '0'; break; case 'A' : case 'B' : case 'C' : case 'D' : case 'E' : case 'F' : ucValue = *szSrc - 'A' + 10; break; case 'a' : case 'b' : case 'c' : case 'd' : case 'e' : case 'f' : ucValue = *szSrc - 'a' + 10; break; default : assert(false); } nCount = snChar / 2; if ( snChar++ % 2 == 0 ) pucOutput[nCount] = ucValue; else pucOutput[nCount] = pucOutput[nCount] << 4 + ucValue; } nCount = (snChar + 1) / 2; pucOutput[nCount] = '\0'; return nCount;}