在 C++ 中等价于 PHP 中的 pack 函数 pack('H*', $tagIdAsHex);

Equivalent in C++ to the pack function in PHP pack('H*', $tagIdAsHex);

我有这个 PHP 代码:

$tagId = 1;    // the original value of tag
$tagIdAsHex = sprintf("%02X", $tagId);    // the tag value in hex format
$tagAsHexBytes = pack('H*', $tagIdAsHex);  // the packed hex value of tag packed into string as a conversion 

如何将其转换为 C++?

byte tagId = 1;
auto hexedTag = IntToHex(tagId); //C++ Builder
??

显示的 PHP 代码只是将整数 1 转换为包含 "01" 的 hex-encoded string,然后解析该十六进制 string 转换为二进制 string 保存单个字节 0x01.

在 C 中,您可以在循环中使用 sscanf() 来解析十六进制字符串。

在标准 C++ 中,您可以在循环中使用 std::hex and std::setw() to parse a hex string from any std::istream, such as std::istringstream, using operator>>

具体在 C++Builder 中,您可以使用其 RTL 的 HexToBin() 函数将十六进制字符串解析为 pre-allocated 字节数组。