简体   繁体   English

如何使用PHP将整数转换为8位二进制数据?

[英]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. 我需要将整数转换为8位,但打包只能转换为16位二进制数据。 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. 这个功能的想法取自Perl,所有格式代码的工作方式与Perl相同。 However, there are some formatting codes that are missing such as Perl's "u" format code. 但是,有一些格式代码丢失,例如Perl的“u”格式代码。

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 请注意,有符号和无符号值之间的区别仅影响函数unpack(),其中函数pack()为有符号和无符号格式代码提供相同的结果

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: 要获得正确的格式并添加像这样00000001的主要zéros,请使用:

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

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

You can use c or C for this. 您可以使用c或C. Like: 喜欢:

pack('C', 234);

c is signed, C is unsigned. c是签名的,C是未签名的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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