Why does PHP substr () change the byte return ASCII byte?

I was going to use a long string to manipulate a large number of bit flags while storing the resulting string in Redis. However, I came across a php (?) Error. A byte containing bits 00001101 using substr() returns an unexpected value:

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

Ideone

Is the assumption that substr() is binary safe? Also tried mb_substr() , setting the encoding to 8bit with exactly the same result.

+6
source share
1 answer

You set $bin to integer 13

Using substr() for $bin is to pour $bin into a string ( "13" )

You are reading the first character of this line ( "1" )

Using printf() with %b , you explicitly return this string to integer 1

the argument is treated as an integer and is represented as a binary number.

EDIT

This code should give the result you expect

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

All Articles