#%#$#%@%@%$#%$#%#%#$%@_e1bfd762321e409c++ee4ac0b6e841963c 的 `pack('h*', $hexstring)` 将十六进制字符串(如 `"01"`)解析为对应的二进制字节序列(如单字节 `\x01`);c++ 中可通过标准库流操作、`sscanf` 或 c++builder 特有函数实现等效逻辑。
在 PHP 中,pack('H*', $tagIdAsHex) 的作用并非“编码”,而是将表示字节的十六进制字符串(不带前缀、偶数长度)解码为原始二进制数据。例如:
这与 sprintf("%02X", n) 的“整数转十六进制字符串”方向相反,属于十六进制字符串到字节数组的解析(hex decode)。
#include#include #include #include #include std::vector hexStringToBytes(const std::string& h ex) { // 移除空格、确保长度为偶数 std::string cleaned; for (char c : hex) { if (std::isxdigit(c)) cleaned += std::toupper(c); } if (cleaned.size() % 2 != 0) { throw std::invalid_argument("Hex string length must be even"); } std::vector
bytes; bytes.reserve(cleaned.size() / 2); for (size_t i = 0; i < cleaned.size(); i += 2) { std::string byteStr = cleaned.substr(i, 2); uint8_t byte; std::istringstream iss("0x" + byteStr); iss >> std::hex >> byte; if (iss.fail()) throw std::invalid_argument("Invalid hex character"); bytes.push_back(byte); } return bytes; } // 使用示例: int main() { uint8_t tagId = 1; std::string hexStr = "01"; // 等价于 PHP 中 sprintf("%02X", tagId) auto binary = hexStringToBytes(hexStr); // 得到 {0x01} // 验证:binary[0] == 0x01 return 0; }
若使用 C++Builder,可直接调用 RTL 函数,更简洁高效:
#include#include std::vector hexStringToBytes_CppBuilder(const UnicodeString& hex) { std::vector result(hex.Length() / 2); int len = HexToBin(hex.c_str(), result.data(), static_cast (result.size())); if (len < 0) throw std::runtime_error("HexToBin failed"); result.resize(len); return result; }
| 场景 | 推荐方法 |
|---|---|
| 跨平台、标准 C++ 项目 | std::istringstream + std::hex 循环解析(如上) |
| 高性能/大量解析 | 手写查表法(256 项 ASCII→nibble 映射) |
| C++Builder 专属项目 | HexToBin()(需包含 |
无需引入第三方库,纯标准 C++ 即可精准复现 PHP pack('H*') 的语义:将十六进制字符串安全、健壮地还原为原始字节序列。
立即学习“PHP免费学习笔记(深入)”;