Nabeel Khan
Nabeel Khan

Reputation: 3993

Bitwise & | operators in octal system

I understand how bitwise operator & and | work for binary numbers. However I'm confused at how they work with octal numbers.

Does the system convert the number to binary first and then perform the operation and then convert back to octal? Or is it variable?

For example if I do either of these:

echo decoct( 0400 & 0500 | 0000 );
echo decoct( 0600 & 0500 | 0000 );

I get 400 as the result.

However, if i do:

echo decoct( 0400 & 0500 | 0100 );
echo decoct( 0600 & 0500 | 0100 );

I get 500 in both cases.

Also, I have seen code where the bitwise operation in PHP without using decoct around it. Does PHP retain it as octal after completion of the operation? or converts it to decimal (and when does it do that?).

Kindly guide me in the right direction to what to study and learn to understand octal (and decimal and others) bitwise operations.

Upvotes: 0

Views: 832

Answers (1)

Progman
Progman

Reputation: 19555

The bitwise operators "luckily" work for binary, octal and hexadecimal presentations of your values/variables. In the end they all will run on a binary level on your values/variables. The grouping of your digits/bits fits perfectly with the bitwise operators.

  0400 = 0b100000000 = 0x100 (0001 0000 0000)
& 0500 = 0b101000000 = 0x140 (0001 0100 0000)
----------------------------
  0400 = 0b100000000 = 0x100 (0001 0000 0000)
| 0100 = 0b001000000 = 0x040 (0000 0100 0000)
----------------------------
  0500 = 0b101000000 = 0x140 (0001 0100 0000)

And for the other expression:

  0600 = 0b110000000 = 0x180 (0001 1000 0000)
& 0500 = 0b101000000 = 0x140 (0001 0100 0000)
----------------------------
  0400 = 0b100000000 = 0x100 (0001 0000 0000)
| 0100 = 0b001000000 = 0x040 (0000 0100 0000)
----------------------------
  0500 = 0b101000000 = 0x140 (0001 0100 0000)

It does works for these representations because a "digit" will always use 1, 3 or 4 bits and no other "digit" can overwrite these "reserved" digits.

The bitwise operations are run on the bits of the values (hence the name). The representation/display of the values are irrelevant for the bitwise operations.

Upvotes: 1

Related Questions