Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/270.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么PHP substr()会更改ASCII回车字节?_Php_Binary Data_Substr - Fatal编程技术网

为什么PHP substr()会更改ASCII回车字节?

为什么PHP substr()会更改ASCII回车字节?,php,binary-data,substr,Php,Binary Data,Substr,我打算使用一个长字符串来处理大量位标志,将结果字符串保留在Redis中。然而,偶然发现了一个php错误(?)。包含使用substr()读取的位00001101的字节返回意外值: $bin = 0b00001101; // 13 - ASCII Carriage return $c = substr($bin, 0, 1); // read this character printf("Expectation: 00001101, reality: %08b\n", $c); // 000

我打算使用一个长字符串来处理大量位标志,将结果字符串保留在Redis中。然而,偶然发现了一个php错误(?)。包含使用
substr()读取的位
00001101
的字节返回意外值:

$bin = 0b00001101;  // 13 - ASCII Carriage return
$c = substr($bin, 0, 1);    // read this character
printf("Expectation: 00001101, reality: %08b\n", $c); // 00000001


假设
substr()
是二进制安全的,这是错误的吗?还尝试了
mb_substr()
,将编码设置为
8bit
,结果完全相同。

您正在将
$bin
设置为整数

$bin
使用
substr()
$bin
强制转换为字符串(
“13”

您正在读取该字符串的第一个字符(
“1”

printf()
%b
一起使用,可以显式地将该字符串转换回整数
1

参数被视为整数,并以二进制数表示

编辑

这段代码应该给出您期望的结果

$bin = 0b00001101;  // 13 - ASCII Carriage return
$c = substr(chr($bin), 0, 1);    // read this character
printf("Expectation: 00001101, reality: %08b\n", ord($c)); // 00001101

谢谢可能是我制造了一个坏例子/隔离了这个问题。最初我有一个较长的二进制字符串,从中读取一个特定的字节。我会重写这个例子。没错,现在我明白了。再次感谢!