C++小字符到十六进制函数

C++ Small char to hex function?

本文关键字:十六进制 函数 字符 C++      更新时间:2023-10-16

我正试图找到一种非常轻量级的方法,通过下面的两个例子来实现对char或md5的十六进制运算。

char example[0x34];
char example_final[0x200];
sprintf(example, "%s", "4E964DCA5996E48827F62A4B7CCDF045");

下面是使用两个PHP函数的示例。

MD5:

sprintf(example_final, "%s", md5(example));
output: 149999b5b26e1fdeeb059dbe0b36c3cb

十六进制:

sprintf(example_final, "%s", bin2hex(example));
output: 3445393634444341353939364534383832374636324134423743434446303435

这是最轻量级的方法。我想用一些大的char数组来表示它的十六进制值,而不是用foreach char做一个循环,但不确定。

bin2hex的示例如下:

#include <string>
#include <iostream>

std::string bin2hex(const std::string& input)
{
    std::string res;
    const char hex[] = "0123456789ABCDEF";
    for(auto sc : input)
    {
        unsigned char c = static_cast<unsigned char>(sc);
        res += hex[c >> 4];
        res += hex[c & 0xf];
    }
    return res;
}

int main()
{
    std::string example = "A string";
    std::cout << "bin2hex of " << example << " gives " << bin2hex(example) << std::endl;
}