0

decbin() converts decimal to binary , also 1 XOR 0 = 1

so , decbin(0) ^ decbin(1) should give me 1 but it is giving me nothing .... why ?

But , if I'm doing other operations , resultant is right...

  1. decbin(0) | decbin(1) => 1

  2. decbin(0) & decbin(1) => 0

  3. decbin(1) & decbin(1) => 1

2 Answers 2

4

Decbin returns a string, and the bitwise operators aren't defined on strings.

Editing my comment into the answer after the question was edited:

Not defined means that they are not meaningfully functional on strings, not that it won't give a seemingly correct answer. Try some other values and I'm pretty sure it won't work. What you have to do is do your operation on integers, and once you're done with all your calculations get the string representation with decbin. See the other answer for binary literal representation.

Sign up to request clarification or add additional context in comments.

2 Comments

but answer for other binary operations is coming correct... only prblm with xor!!
Not defined means that they are not meaningfully functional on strings, not that it won't give a seemingly correct answer. Try some other values and I'm pretty sure it won't work. What you have to do is do your operation on integers, and once you're done with all your calculations get the string representation with decbin. See the other answer for binary literal representation.
2

In PHP 5.4+ you have avalible the binary syntax via the 0b prefix:

$res = 0b00 ^ 0b01

To your edit: the result is correct by accident. The values you gave are casted back and forward to strings and then to numbers again. Try using larger numbers, and it will fail. Bitwise operators don't fail on strings (as they should) because they are implicitly casted to numbers.

You can always perform the operation on normal integers, and then just display the output in binary:

$res = 1 ^ 0;
echo decbin($res);

This also works:

$res = 15 ^ 7;
echo decbin($res);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.