简体   繁体   中英

C++ equivalent of PHP's pack()

My question is simple.

Is there an equivalent of PHP's pack() and unpack() function in the C++ STL? If no, is there an alternative to achieve the same goal?

https://www.php.net/pack

Thanks.

If your goal is serializing data, you can use Google protocol buffers to achieve it.

http://code.google.com/apis/protocolbuffers/

There is no serialization mechanism in the STL. Depending on what you want to do you could either use a library such as the one in Boost or you could write your own serialization code , which can be a viable alternative especially if your data is rather simple.

A while back I wrote a small a library in C that does this functionality. I placed my code on Google code here: code.google.com/p/packlib/

Structs are very much like the unpack function within PHP.

These pieces of code, are basically equivalent.

PHP:

define('ISP_TINY', 4);
class IS_TINY
{
    const PACK = 'CCCC';
    const UNPACK = 'CSize/CType/CReqI/CSubT';

    public $Size = 4;
    public $Type = ISP_TINY;
    public $ReqI;
    public $SubT;

    public function __construct($rawPacket)
    {
        $pkClass = unpack($this::UNPACK, $rawPacket);
        foreach ($this as $property => $value)
        {
            $this->$property = $pkClass[$property];
        }
    }
}

C++:

#define ISP_TINY = 4;
struct IS_TINY // General purpose 4 byte packet
{
    byte Size; // Always 4
    byte Type; // Always ISP_TINY
    byte ReqI;
    byte SubT;
};

A while ago I needed the same functionality so I wrote a single-header library for this. It supports most of the functionality from php's pack() / unpack() . The library is available on github here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM