Subversion Repositories oidplus

Rev

Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

  1. <?php
  2.  
  3. /*
  4.  * binary.class.php:
  5.  * Utility functions for dealing with binary files/strings.
  6.  * All functions assume network byte order (big-endian).
  7.  *
  8.  * Copyright (C) 2008, 2009 Patrik Fimml
  9.  * Copyright (c) 2023 Daniel Marschall
  10.  *
  11.  * This file is part of glip.
  12.  *
  13.  * glip is free software: you can redistribute it and/or modify
  14.  * it under the terms of the GNU General Public License as published by
  15.  * the Free Software Foundation, either version 2 of the License, or
  16.  * (at your option) any later version.
  17.  
  18.  * glip is distributed in the hope that it will be useful,
  19.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  21.  * GNU General Public License for more details.
  22.  *
  23.  * You should have received a copy of the GNU General Public License
  24.  * along with glip.  If not, see <http://www.gnu.org/licenses/>.
  25.  */
  26.  
  27. namespace ViaThinkSoft\Glip;
  28.  
  29. final class Binary
  30. {
  31.         static public function uint16($str, $pos = 0) {
  32.                 return ord($str[$pos + 0]) << 8 | ord($str[$pos + 1]);
  33.         }
  34.  
  35.         static public function uint32($str, $pos = 0) {
  36.                 $a = unpack('Nx', substr($str, $pos, 4));
  37.                 return $a['x'];
  38.         }
  39.  
  40.         static public function nuint32($n, $str, $pos = 0) {
  41.                 $r = array();
  42.                 for ($i = 0; $i < $n; $i++, $pos += 4)
  43.                         $r[] = Binary::uint32($str, $pos);
  44.                 return $r;
  45.         }
  46.  
  47.         static public function fuint32($f) {
  48.                 return Binary::uint32(fread($f, 4));
  49.         }
  50.  
  51.         static public function nfuint32($n, $f) {
  52.                 return Binary::nuint32($n, fread($f, 4 * $n));
  53.         }
  54.  
  55.         static public function git_varint($str, &$pos = 0) {
  56.                 $r = 0;
  57.                 $c = 0x80;
  58.                 for ($i = 0; $c & 0x80; $i += 7) {
  59.                         $c = ord($str[$pos++]);
  60.                         $r |= (($c & 0x7F) << $i);
  61.                 }
  62.                 return $r;
  63.         }
  64. }
  65.