Skip to content

Instantly share code, notes, and snippets.

@jesseschalken
Last active December 11, 2015 09:08
Show Gist options
  • Save jesseschalken/4577886 to your computer and use it in GitHub Desktop.
Save jesseschalken/4577886 to your computer and use it in GitHub Desktop.
Simple serialization format
<?php
function serialize_uint($x) {
for ($r = ''; $x > 0; $x = $x >> 8)
$r = chr($x & 0xFF) . $r;
return chr(strlen($r)) . $r;
}
function serialize_str($s) {
return serialize_uint(strlen($s)) . $s;
}
function deserialize_uint($s, &$i = 0) {
$e = $i + ord($s[$i++]);
for ($r = 0; $i < $e; $i++)
$r = ($r << 8) | ord($s[$i]);
return $r;
}
function deserialize_str($s, &$i = 0) {
$l = deserialize_uint($s, $i);
$r = substr($s, $i, $l);
$i += $l;
return $r;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment