3 # Copyright (C) 2007 Jason Woofenden
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 # This file contains code to work with "raw" binary numbers in big-endian format
22 # return a 4 byte string that represent the passed integer as a big-endian binary number
23 function to_raw_int($int) {
24 return chr($int >> 24) . chr(($int >> 16) & 0xff) . chr(($int >> 8) & 0xff) . chr($int & 0xff);
27 # return a php number from the string you pass in. The first 4 bytes of the
28 # string are read in as a binary value in big-endian format.
29 function from_raw_int($quad) {
30 return (ord(substr($quad, 0, 1)) << 24) + (ord(substr($quad, 1, 1)) << 16) + (ord(substr($quad, 2, 1)) << 8) + ord(substr($quad, 3, 1));
33 function int_at($string, $index) {
34 return from_raw_int(substr($string, $index * 4, 4));
37 # remove the first 4 bytes of the string, and return them as an int
38 function pop_int(&$string) {
39 $int = from_raw_int(substr($string, 0, 4));
40 $string = substr($string, 4);
44 # convert an array (not hash) to a string of bytes
45 function array_to_raw($data) {
46 $ret = to_raw_int(count($data));
47 foreach($data as $dat) {
48 $ret .= to_raw_int(strlen($dat));
54 function raw_to_array($data) {
55 $header_count = pop_int($data);
57 while($header_count--) {
58 $size = pop_int($data);
59 $ret[] = substr($data, 0, $size);
60 $data = substr($data, $size);