我想构建一个函数来轻松地将包含十六进制代码的字符串(例如“0ae34e”)转换为包含等效 ascii 值的字符串,反之亦然。
我是否必须将十六进制字符串切成两个值对,然后再次将它们组合在一起,或者是否有一种方便的方法可以做到这一点?
thanks
基于binascii_unhexlify()来自 Python 的函数:
#include <cctype> // is*
int to_int(int c) {
if (not isxdigit(c)) return -1; // error: non-hexadecimal digit found
if (isdigit(c)) return c - '0';
if (isupper(c)) c = tolower(c);
return c - 'a' + 10;
}
template<class InputIterator, class OutputIterator> int
unhexlify(InputIterator first, InputIterator last, OutputIterator ascii) {
while (first != last) {
int top = to_int(*first++);
int bot = to_int(*first++);
if (top == -1 or bot == -1)
return -1; // error
*ascii++ = (top << 4) + bot;
}
return 0;
}
Example
#include <iostream>
int main() {
char hex[] = "7B5a7D";
size_t len = sizeof(hex) - 1; // strlen
char ascii[len/2+1];
ascii[len/2] = '\0';
if (unhexlify(hex, hex+len, ascii) < 0) return 1; // error
std::cout << hex << " -> " << ascii << std::endl;
}
Output
7B5a7D -> {Z}
源代码中的注释中引用了一段有趣的内容:
当我阅读数十个编码或解码的程序时
格式在这里(文档?hihi:-)我已经制定了 Jansen 的格式
观察:
以 ASCII 编码二进制数据的程序是这样编写的
它们尽可能不可读。使用的设备包括
不必要的全局变量,将重要的表埋在不相关的表中
源文件,将函数放入包含文件中,使用
看似描述性的变量名称用于不同的目的,调用
空子例程和许多其他子例程。
我试图打破这个传统,但我想那
确实使性能次优。哦,好吧,太糟糕了...
杰克·詹森 (Jack Jansen),CWI,1995 年 7 月。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)