Search code examples
phpc++arrayshex

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


I have this PHP code:

$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 

How can I translate that to C++?

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

Solution

  • The PHP code shown is simply converting the integer 1 into a hex-encoded string containing "01", and is then parsing that hex string into a binary string holding a single byte 0x01.

    In C, you can use sscanf() in a loop to parse a hex string.

    In standard C++, you can use std::hex and std::setw() to parse a hex string from any std::istream, such as std::istringstream, using operator>> in a loop.

    In C++Builder specifically, you can use its RTL's HexToBin() function to parse a hex string into a pre-allocated byte array.