I want to encode an int16 value in 15 bits and leave the leftmost bit as a flag. Then I want to read the bytes and decode to decimal the rightmost 15 bits as the integer. Is this possible?
$value = 49;
$packed = pack('S', $value); // returns correct hex
$formatted = $packed ^ 0b1000000000000000; // returns too long number - 4 bytes instead of 2
How can I do this?
Use bitwise operators.
You have got your number in to $packed
.
Let the $encoded
be your target.
Save the $packed
to the $encoded
$encoded = $packed;
$encoded = $encoded | 0b1000000000000000; //Set the MSB
Lets read it back
$encoded = $encoded $ 0b0111111111111111; //Clear the MSB first
$packed = $encoded; //The rest is automatically the value