Shifting bits of a binary string

From: Date: Sun, 13 Apr 2014 12:20:49 +0000
Subject: Shifting bits of a binary string
Groups: php.internals 
Request: Send a blank email to [email protected] to get a copy of this message
Hi List,

I hope I'm on the right list but I can't find any other helpful.

I have a binary string and I would like to work with bitwise operators.
The only help I found was to convert it to an integer. That's ok but it results in some questions:

 - What if the binary data is more than 32/64 bits long?
 - Why converting binary data of form one into binary data of another form only to manipulate bits?

So I simply tested what's going on if I operate on a string directly but on shifting I get the same wrong result every time.
(Testscript below)

On reading the manual the only note for strings are the following:
(http://www.php.net/manual/en/language.operators.bitwise.php)
Be aware of data type conversions. If both the left-hand and right-hand parameters are strings, the bitwise operator will operate on the characters' ASCII values.
Why such bit operators doesn't work with strings? Why there is not helpful information about in the manual. Why on operation something not working doesn't result in an error/notice but in a completely unexpected value? Greetings Marc Shift to the left: var_dump(decbin(ord(chr(1)))); for ($i=0; $i<10; $i++) {
    var_dump(decbin(ord(chr(1) << $i)));
} Output: string(1) "1" string(6) "110000" string(6) "110000" string(6) "110000" string(6) "110000" string(6) "110000" string(6) "110000" string(6) "110000" string(6) "110000" string(6) "110000" string(6) "110000" Shift to the right: var_dump(decbin(ord(chr(32)))); for ($i=0; $i<10; $i++) {
    var_dump(decbin(ord(chr(32) >> $i)));
} Output: string(1) "100000" string(6) "110000" string(6) "110000" string(6) "110000" string(6) "110000" string(6) "110000" string(6) "110000" string(6) "110000" string(6) "110000" string(6) "110000" string(6) "110000"

Thread (7 messages)

« previous php.internals (#73681) next »