3 # This program is in the public domain within the United States. Additionally,
4 # we waive copyright and related rights in the work worldwide through the CC0
5 # 1.0 Universal public domain dedication, which can be found at
6 # http://creativecommons.org/publicdomain/zero/1.0/
9 # This file contains code to work with "raw" binary numbers in big-endian format
12 # return a 4 byte string that represent the passed integer as a big-endian binary number
13 function to_raw_int($int) {
14 return chr($int >> 24) . chr(($int >> 16) & 0xff) . chr(($int >> 8) & 0xff) . chr($int & 0xff);
17 # return a php number from the string you pass in. The first 4 bytes of the
18 # string are read in as a binary value in big-endian format.
19 function from_raw_int($quad) {
20 return (ord(substr($quad, 0, 1)) << 24) + (ord(substr($quad, 1, 1)) << 16) + (ord(substr($quad, 2, 1)) << 8) + ord(substr($quad, 3, 1));
23 function int_at($string, $index) {
24 return from_raw_int(substr($string, $index * 4, 4));
27 # remove the first 4 bytes of the string, and return them as an int
28 function pop_int(&$string) {
29 $int = from_raw_int(substr($string, 0, 4));
30 $string = substr($string, 4);
34 # convert an array (not hash) to a string of bytes
35 function array_to_raw($data) {
36 $ret = to_raw_int(count($data));
37 foreach($data as $dat) {
38 $ret .= to_raw_int(strlen($dat));
44 function raw_to_array($data) {
45 $header_count = pop_int($data);
47 while($header_count--) {
48 $size = pop_int($data);
49 $ret[] = substr($data, 0, $size);
50 $data = substr($data, $size);