#%#$#%@%@%$#%$#%#%#$%@_e1bfd762321e409c++ee4ac0b6e841963c 的 `pack('h*', $hexstring)` 将十六进制字符串(如 `"01"`)解析为对应的二进制字节序列(如 `"\x01"`)。在 c++ 中,可通过标准库流操作、`sscanf` 或 c++builder 特有函数实现等效转换。
PHP 代码中:
$tagId = 1;
$tagIdAsHex = sprintf("%02X", $tagId); // → "01"
$tagAsHexBytes = pack('H*', $tagIdAsHex); // → binary string of length 1: \x01其本质是两步:
使用 std::istringstream + std::hex 解析偶数长度的十六进制字符串:
#include#include #include #include #include std::vector hexStringToBytes(const std::string& hex) { if (hex.length() % 2 != 0) { throw std::invalid_argument("Hex string length must be even"); } std::vector bytes; bytes.reserve(hex.length() / 2); for (size_t i = 0; i < hex.length(); i += 2) { std::string byteStr = hex.substr(i, 2); unsigned int byteVal; std::istringstream iss(byteStr); iss >> std::hex >> byteVal; if (!iss || byteVal > 0xFF) { throw std::invalid_argument("Invalid hex byte: " + byteStr); } bytes.push_back(static_cast (byteVal)); } return bytes; } // 示例用法 int main() { uint8_t tagId = 1; std::string hexedTag = fmt::format("{:02X}", tagId); // C++20: std::format;或用 std::ostringstream auto binaryBytes = hexStringToBytes(hexedTag); // → {0x01} // 验证:binaryBytes.size() == 1, binaryBytes[0] == 0x01 }
? 提示:若未使用 C++20 std::format,可用 std::ostringstream 生成十六进制字符串:std::ostringstream oss; oss
若在 Embarcadero C++Builder 环境中开发,可直接调用 RTL 提供的 HexToBin():
立即学习“PHP免费学习笔记(深入)”;
#include#include std::vector hexStringToBytes_Builder(const AnsiString& hex) { std::vector buffer(hex.Length() / 2); int actualLen = HexToBin(hex.c_str(), buffer.data(), buffer.size()); if (actualLen < 0) { throw std::runtime_error("HexToBin failed"); } buffer.resize(actualLen); return buffer; }
⚠️ 注意事项:
且仅含 0–9、A–F、a–f 字符; ✅ 总结:最通用、可移植的 C++ 等效实现是「std::istringstream + std::hex」解析法,它精准复现了 PHP pack('H*') 的语义:将规范十六进制字符串无损还原为原始二进制字节流。