简体   繁体   中英

integer to 4 bit binary php using pack function

How to send integer value 1 as 0001 binary in php? I am trying as pack('I','0001') . I have also tried ('h*','0x01') . Output should be just 2 bytes of data.

Just use decbin function:

$i=1
echo "00".decbin($i); //outputs 0001

You can use the decbin() function with the str_pad() function to accomplish this. By using str_pad() versuses hardcoding the leading 0 's, you can optionally control the length of your output, extending or reducing it at any time by manipulating the second pad_length argument.

$num = 1;
$len = 4;
echo str_pad(decbin($num), $len, "0", STR_PAD_LEFT);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM