A helper class to convert integer to binary strings and vice versa. Useful for writing and reading integers to / from files or sockets.
public static functionint8($i) {
returnis_int($i) ?pack("c",$i) :unpack("c",$i)[1];
}
public static functionuInt8($i) {
returnis_int($i) ?pack("C",$i) :unpack("C",$i)[1];
}
public static functionint16($i) {
returnis_int($i) ?pack("s",$i) :unpack("s",$i)[1];
}
public static functionuInt16($i,$endianness=false) {$f=is_int($i) ?"pack":"unpack";
if ($endianness===true) {// big-endian$i=$f("n",$i);
}
else if ($endianness===false) {// little-endian$i=$f("v",$i);
}
else if ($endianness===null) {// machine byte order$i=$f("S",$i);
}
returnis_array($i) ?$i[1] :$i;
}
public static functionint32($i) {
returnis_int($i) ?pack("l",$i) :unpack("l",$i)[1];
}
public static functionuInt32($i,$endianness=false) {$f=is_int($i) ?"pack":"unpack";
if ($endianness===true) {// big-endian$i=$f("N",$i);
}
else if ($endianness===false) {// little-endian$i=$f("V",$i);
}
else if ($endianness===null) {// machine byte order$i=$f("L",$i);
}
returnis_array($i) ?$i[1] :$i;
}
public static functionint64($i) {
returnis_int($i) ?pack("q",$i) :unpack("q",$i)[1];
}
public static functionuInt64($i,$endianness=false) {$f=is_int($i) ?"pack":"unpack";
if ($endianness===true) {// big-endian$i=$f("J",$i);
}
else if ($endianness===false) {// little-endian$i=$f("P",$i);
}
else if ($endianness===null) {// machine byte order$i=$f("Q",$i);
}
returnis_array($i) ?$i[1] :$i;
}
}?>
Usage example:
Header("Content-Type: text/plain");
include("int_helper.php");
echoint_helper::uInt8(0x6b) .PHP_EOL;// kechoint_helper::uInt8(107) .PHP_EOL;// kechoint_helper::uInt8("\x6b") .PHP_EOL.PHP_EOL;// 107echoint_helper::uInt16(4101) .PHP_EOL;// \x05\x10echoint_helper::uInt16("\x05\x10") .PHP_EOL;// 4101echoint_helper::uInt16("\x05\x10",true) .PHP_EOL.PHP_EOL;// 1296echoint_helper::uInt32(2147483647) .PHP_EOL;// \xff\xff\xff\x7fechoint_helper::uInt32("\xff\xff\xff\x7f") .PHP_EOL.PHP_EOL;// 2147483647
// Note: Test this with 64-bit build of PHPechoint_helper::uInt64(9223372036854775807) .PHP_EOL;// \xff\xff\xff\xff\xff\xff\xff\x7fechoint_helper::uInt64("\xff\xff\xff\xff\xff\xff\xff\x7f") .PHP_EOL.PHP_EOL;// 9223372036854775807?>