C++ char十六进制值到字节

mat*_*w3r -5 c++ hex

我在char指针中有一个十六进制值(例如'F3'),我想将它转换为byte,因为我希望它放入一个数组.我知道有很多解决方案,但它们不是我想要的.

提前致谢!

编辑:

好吧,也许我没有写过一切.我现在拥有的:

char aChar[5];
itoa (j, aChar, 16);
Run Code Online (Sandbox Code Playgroud)

j现在是3,我只想要它在字节中.Atoi,scanf没有帮助,那些是不同的解决方案.

Joh*_*web 6

既然你已经标记了这个C++而不是C,我就不会使用任何C函数(除了assert()演示行为,边缘条件).这是一个示例文件.我们称之为hex2byte.cpp:

#include <sstream>
#include <cassert>

unsigned char hex2byte(const char* hex)
{
    unsigned short byte = 0;
    std::istringstream iss(hex);
    iss >> std::hex >> byte;
    return byte % 0x100;
}

int main()
{
    const char* hex = "F3";
    assert(hex2byte(hex) == 243);
    assert(hex2byte("") == 0);
    assert(hex2byte("00") == 0);
    assert(hex2byte("A") == 10);
    assert(hex2byte("0A") == 10);
    assert(hex2byte("FF") == 255);
    assert(hex2byte("EEFF") == 255);
    assert(hex2byte("GG") == 00);
    assert(hex2byte("a") == 10);
    assert(hex2byte("0a") == 10);
    assert(hex2byte("f3") == 243);
    assert(hex2byte("ff") == 255);
    assert(hex2byte("eeff") == 255);
    assert(hex2byte("gg") == 00);
}
Run Code Online (Sandbox Code Playgroud)

做了:

% make hex2byte
g++ -Wall -Wextra -Wshadow -pedantic -Weffc++ -Werror hex2byte.cpp -o hex2byte
Run Code Online (Sandbox Code Playgroud)

运行:

% ./hex2byte
Run Code Online (Sandbox Code Playgroud)

没有断言.添加错误处理的味道(如检查时hex == NULL,等等).