Reputation: 31
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
Upvotes: 1
Views: 840
Reputation: 11
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
Upvotes: 1