Last active
December 11, 2015 09:08
-
-
Save jesseschalken/4577886 to your computer and use it in GitHub Desktop.
Simple serialization format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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