简体   繁体   中英

How to convert integer to 8bit binary data by using PHP?

I need to convert integer to 8bit, but pack just only can convert to 16bit binary data. I search in Google and can not get anthing. can someone help?

echo $test = pack('C', 1);

Pack given arguments into binary string according to format.

The idea for this function was taken from Perl and all formatting codes work the same as in Perl. However, there are some formatting codes that are missing such as Perl's "u" format code.

Note that the distinction between signed and unsigned values only affects the function unpack(), where as function pack() gives the same result for signed and unsigned format codes

Codes are

a   NUL-padded string
A   SPACE-padded string
h   Hex string, low nibble first
H   Hex string, high nibble first
c   signed char
C   unsigned char
s   signed short (always 16 bit, machine byte order)
S   unsigned short (always 16 bit, machine byte order)
n   unsigned short (always 16 bit, big endian byte order)
v   unsigned short (always 16 bit, little endian byte order)
i   signed integer (machine dependent size and byte order)
I   unsigned integer (machine dependent size and byte order)
l   signed long (always 32 bit, machine byte order)
L   unsigned long (always 32 bit, machine byte order)
N   unsigned long (always 32 bit, big endian byte order)
V   unsigned long (always 32 bit, little endian byte order)
f   float (machine dependent size and representation)
d   double (machine dependent size and representation)
x   NUL byte
X   Back up one byte
@   NUL-fill to absolute position

To get right format and add leading zéros like this 00000001 use this:

<?php
// Add leading zeros
$bin = sprintf( "%08d", decbin( 26 )); // "00011010"
?>

Answer in http://php.net/manual/en/function.decbin.php

You can use c or C for this. Like:

pack('C', 234);

c is signed, C is unsigned.

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