处理从十六进制到十六进制的转换

Handling of conversions from and to hex

本文关键字:十六进制 转换 处理      更新时间:2023-10-16

我想构建一个函数,轻松地将包含十六进制代码的字符串(例如"0ae34e")转换为包含等效ascii值的字符串,反之亦然。我必须将十六进制字符串切割成两个值,然后再次将它们拼接在一起吗?或者有一种方便的方法可以做到这一点吗?

感谢

基于Python中的binascii_unhexlify()函数:

#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;
}

示例

#include <iostream>
int main() {
  char hex[] = "7B5a7D";
  size_t len = sizeof(hex) - 1; // strlen
  char ascii[len/2+1];
  ascii[len/2] = '';
  if (unhexlify(hex, hex+len, ascii) < 0) return 1; // error
  std::cout << hex << " -> " << ascii << std::endl;
}

输出

7B5a7D -> {Z}

一个有趣的引用源代码中的评论:

当我阅读几十个编码或解码这里的格式(文档?嗨:-)我已经制定了Jansen的观察:

用ASCII编码二进制数据的程序就是这样编写的它们尽可能不可读。使用的设备包括不必要的全局变量,将重要表隐藏在不相关的表中源文件,将函数放入包含文件中,使用用于不同目的的看似描述性的变量名,调用空的子例程和大量其他子例程。

我试图打破这个传统,但我想确实使性能处于次优状态。哦,太糟糕了。。。

Jack Jansen,CWI,1995年7月。

sprintfsscanf函数已经可以为您完成此操作。这段代码是一个应该给你一个想法的例子。在使用之前,请仔细查看功能参考和安全替代方案

#include <stdio.h>
int main()
{
 int i;
 char str[80]={0};
 char input[80]="0x01F1";
 int output;
 /* convert a hex input to integer in string */
 printf ("Hex number: ");
 scanf ("%x",&i);
 sprintf (str,"%d",i,i);
 printf("%sn",str);
/* convert input in hex to integer in string */
 sscanf(input,"%x",&output);
 printf("%dn",output);
}

如果你想使用一种更为c++原生的方式,你可以说

std::string str = "0x00f34" // for example
stringstream ss(str);
ss << hex;
int n;
ss >> n;