JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
metaform: merge ckeditor settings from cms
[wfpl.git] / binary.php
1 <?php
2
3 #  Copyright (C) 2007 Jason Woofenden
4 #
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.
9 #  
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.
14 #  
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/>.
17
18
19 # This file contains code to work with "raw" binary numbers in big-endian format
20
21
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);
25 }
26
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));
31 }
32
33 function int_at($string, $index) {
34         return from_raw_int(substr($string, $index * 4, 4));
35 }
36
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);
41         return $int;
42 }
43
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));
49                 $ret .= $dat;
50         }
51         return $ret;
52 }
53
54 function raw_to_array($data) {
55         $header_count = pop_int($data);
56         $ret = array();
57         while($header_count--) {
58                 $size = pop_int($data);
59                 $ret[] = substr($data, 0, $size);
60                 $data = substr($data, $size);
61         }
62         return $ret;
63 }
64
65 ?>