其他分享
首页 > 其他分享> > 缺少来自C hex2bin的标点符号

缺少来自C hex2bin的标点符号

作者:互联网

在GCC / Linux C中尝试复制PHP的bin2hex($s)和pack(‘H *’,$s)(又名PHP 2.4.3中的hex2bin($s))时,我似乎已经弄明白了,除了它是因某些奇怪的原因丢弃标点符号.你能弄清楚我在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

解决方法:

好吧,袖子卷起来:让我们来看看C版:

Live on Coliru

>除非你需要,否则不要使用C字符串(sprintf构建一个双字符串不是……效率很高)
>使用iostreams对十六进制数字进行编码/解码(std :: hex)
> hex2bin可以优化,但我选择“更简单”
>我在hex2bin上添加了一些输入清理

#include <string>
#include <sstream>
#include <iomanip>

std::string bin2hex(std::string const &s) {
    std::ostringstream oss;

    for (unsigned char ch : s)
        oss << std::hex << std::setw(2) << std::setfill('0') << (int) ch;

    return oss.str();
}

#include <cassert>
std::string hex2bin(std::string const& s) {
    assert(s.length() % 2 == 0);

    std::string sOut;
    sOut.reserve(s.length()/2);

    std::string extract;
    for (std::string::const_iterator pos = s.begin(); pos<s.end(); pos += 2)
    {
        extract.assign(pos, pos+2);
        sOut.push_back(std::stoi(extract, nullptr, 16));
    }
    return sOut;
}

#include <iostream>
int main() {
    std::cout << "ENCODED: " << bin2hex("This is a 123 test.")          << "\n";
    std::cout << "DECODED: " << hex2bin(bin2hex("This is a 123 test.")) << "\n";
}

输出:

ENCODED: 5468697320697320612031323320746573742e
DECODED: This is a 123 test.

标签:c,string,printf,hex,binary-data
来源: https://codeday.me/bug/20190928/1825889.html