You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++ 如何将十六进制格式std::string转换为BYTE数组

实现步骤

1. 编写十六进制字符串转BYTE数组的转换函数

仅依赖标准库实现,无需引入第三方组件:

#include <string>
#include <vector>
#include <stdexcept>
// 注:BYTE为Windows平台默认定义的无符号字节类型,等价于unsigned char
std::vector<BYTE> HexStrToBytes(const std::string& hexStr) {
    // 校验输入合法性:十六进制字符串长度必须为偶数(2个字符对应1个字节)
    if (hexStr.size() % 2 != 0) {
        throw std::invalid_argument("十六进制字符串长度不能为奇数");
    }
    std::vector<BYTE> bytes;
    bytes.reserve(hexStr.size() / 2);
    for (size_t i = 0; i < hexStr.size(); i += 2) {
        // 逐2位截取字符串,转换为16进制数值
        std::string byteSeg = hexStr.substr(i, 2);
        BYTE val = static_cast<BYTE>(std::stoul(byteSeg, nullptr, 16));
        bytes.push_back(val);
    }
    return bytes;
}

2. 替换原有SCardTransmit调用逻辑

转换后的std::vector<BYTE>可以直接适配接口传参要求:

std::string APDU_Cmd1 = "A0A40000023F00";
std::vector<BYTE> cmdBytes = HexStrToBytes(APDU_Cmd1);
// 直接传入vector存储的数组地址和长度即可
lReturn = SCardTransmit(hCardHandle, &pioSendPci, cmdBytes.data(), static_cast<DWORD>(cmdBytes.size()), NULL, pbRecv, &dwRecv);

注意事项

  • 输入的十六进制字符串不要包含空格、分隔符等非十六进制字符,仅允许0-9、a-f、A-F字符
  • 如果使用C++11之前的标准,std::vector没有data()方法,可以替换为&cmdBytes[0]获取数组首地址
  • 可根据业务需要补充非法字符校验逻辑,避免转换异常

内容的提问来源于stack exchange,提问作者Ma7moud.fadl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 04:57:00