pack php,PHP: pack - Manual

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?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值