1

i've a Modbus response that is a 16bit byte. Every bit or couple of bit mean a specific state. (D15-14: Input volt status, D13: Charging mosfet is short, and so on).

I would like a easy way to print a string every time a single bit is different from previous.

For example: if the digit "14" changes, print "New volt status: Normal" if in the same time changes the D13 too, print "Charging mosfet is short".

I ended up with a not-elegant solution: a xor between the two values in order to check in which bit there is a change and then a for cycle through the XOR bits and than when the bit is on check the index of the bit and than many if (if $bit is 0 than "Mosfet is ok" else "Mosfet is in short"...

There is a quickest way? Thanx

2
  • you could print your number in binay into a string with something like $one_char_per_bit = sprintf("%016b", $Modbus_word), and then access each bit as a 0 or 1 character. Commented Feb 21, 2016 at 18:54
  • Bit wise operator in the Manual Commented Feb 21, 2016 at 19:07

1 Answer 1

1

as RiggiFolly directed.. you use the Binary operators:

<?php
    $value = 5;
    for($iShift = 0; $iShift < 8; $iShift++) {
        if($value & (1 << $iShift)) {
            echo "Bit " . ($iShift+1) . "  IS set\n";
        } else {
            echo "Bit " . ($iShift+1) . " NOT set\n";
        }
    }
?>

Hope that helps.. DNM

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

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.