c++ - 如何将 ASCII 字符串转换为十六进制?

标签 c++ visual-c++

我试图在网上找到这个主题,但找不到我需要的那个。

我有一串字符:

char * tempBuf = "qj";

我想要的结果是0x716A,这个值将被转换成十进制值。

vc++ 中是否有任何函数可用于此目的?

最佳答案

您可以使用字符串流将每个字符转换为十六进制表示形式。

#include <iostream>
#include <sstream>
#include <cstring>

int main()
{
    const char* tempBuf = "qj";

    std::stringstream ss;

    const char* it = tempBuf;
    const char* end = tempBuf + std::strlen(tempBuf);

    for (; it != end; ++it)
        ss << std::hex << unsigned(*it);

    unsigned result;
    ss >> result;

    std::cout << "Hex value: " << std::hex << result << std::endl;
    std::cout << "Decimal value: " << std::dec << result << std::endl;
}

关于c++ - 如何将 ASCII 字符串转换为十六进制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5427744/

相关文章:

C++ 数字输入验证

c++ - 限制数组类型的大小,同时还没有实例

c++ - 将 void* 作为 std::unordered_map 的第二个模板参数是什么意思?

c++ - 结构原型(prototype)

c++ - 将缺少初始值设定项的数组作为参数传递时编译失败

c++ - 对于看起来非常好的 C++ 代码,VC++ 中的错误?

c++ - 读取/写入流时丢失数据

c++ - 在静态初始化程序中使用 getenv() 是否安全,即在 main() 之前?

C++ std::string 参数是 <Bad Ptr>

c++ - 获取 COM 设备的描述