tags:

views:

207

answers:

3

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?

http://us.php.net/pack

Thanks.

+3  A: 

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

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

Stephen
+2  A: 

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:

See http://www.boost.org/doc/libs/1_42_0/libs/serialization/doc/index.html

or you could write your on serialization Code, which can be a viable alternative especially if your data is rather simple.

In that case you might want to take a look at: http://www.parashift.com/c++-faq-lite/serialization.html

Garns
A: 

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;
};
Mark Tomlin