在尝试在 GCC/Linux C++ 中复制 PHPbin2hex($s)
和pack('H*',$s)
(hex2bin($s)
在 PHP 5.4.3+ 中)时,我似乎已经弄清楚了,只是因为某些奇怪的原因它正在删除标点符号。你能弄清楚我在 hex2bin() 函数中可能做错了什么吗?我将 PHP 的 bin2hex() 与我的进行了比较,它似乎在那里正常工作,所以问题出在 hex2bin() 中。
#include <strings.h>
#include <string>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
string bin2hex(string s) {
int nLen = s.length();
string sOut;
char cBuff[2];
for (int i = 0; i < nLen; i++) {
sprintf(cBuff,"%.2x",s[i]);
sOut.append(cBuff);
cBuff[0] = '\0';
}
return sOut;
}
string hex2bin(string s) {
int nLen = s.length();
string sOut;
char cBuff1[2];
char cBuff2[2];
char cBuff[1];
int n,n1,n2;
for (int i = 0; i <= nLen; i+=2) {
sprintf(cBuff1,"%c",s[i]);
sprintf(cBuff2,"%c",s[i+1]);
n1 = atoi(cBuff1);
n2 = atoi(cBuff2);
n = (n1 * 16) + n2;
sprintf(cBuff,"%c",n);
sOut.append(cBuff);
cBuff[0] = '\0';
cBuff1[0] = '\0';
cBuff2[0] = '\0';
}
return sOut;
}
int main() {
string s;
string sResult;
s = "This is a 123 test.";
sResult = bin2hex(s);
printf("ENCODED: %s\n",sResult.c_str());
sResult = hex2bin(sResult);
printf("UNENCODED: %s\n",sResult.c_str());
return 1;
}
这发出:
ENCODED: 5468697320697320612031323320746573742e
UNENCODED: This is a 123 test