PHPDaemon\Utils\Binary::int2bytes PHP Method

int2bytes() public static method

Converts integer to binary string
public static int2bytes ( integer $len, integer $int, boolean $l = false ) : string
$len integer Length
$int integer Integer
$l boolean Optional. Little endian. Default value - false
return string Resulting binary string
    public static function int2bytes($len, $int = 0, $l = false)
    {
        $hexstr = dechex($int);
        if ($len === null) {
            if (mb_orig_strlen($hexstr) % 2) {
                $hexstr = "0" . $hexstr;
            }
        } else {
            $hexstr = str_repeat('0', $len * 2 - mb_orig_strlen($hexstr)) . $hexstr;
        }
        $bytes = mb_orig_strlen($hexstr) / 2;
        $bin = '';
        for ($i = 0; $i < $bytes; ++$i) {
            $bin .= chr(hexdec(substr($hexstr, $i * 2, 2)));
        }
        return $l ? strrev($bin) : $bin;
    }

Usage Example

Beispiel #1
0
 /**
  * Builds length-encoded binary string
  * @param  string $s String
  * @return string    Resulting binary string
  */
 public function buildLenEncodedBinary($s)
 {
     if ($s === NULL) {
         return "©";
     }
     $l = strlen($s);
     if ($l <= 250) {
         return chr($l) . $s;
     }
     if ($l <= 0xffff) {
         return "ª" . Binary::int2bytes(2, true) . $s;
     }
     if ($l <= 0xffffff) {
         return "¬" . Binary::int2bytes(3, true) . $s;
     }
     return Binary::int2bytes(8, $l, true) . $s;
 }