need this function in php :/ and i'm struggling with >>>= operators!? please help to convert this javascript function to php - thank you <3
function calcValues(variant) {
var shape = variant & 0xFF;
variant >>>= 8;
var pattern = variant & 0xFF;
variant >>>= 8;
var baseColor = variant & 0xFF;
variant >>>= 8;
var patternColor = variant & 0xFF;
console.log(shape, pattern,baseColor,patternColor);
}
CodePudding user response:
<?php
function calcValues($variant) {
$shape = $variant & 0xFF;
$variant=$variant >> 8;
$pattern = $variant & 0xFF;
$variant=$variant >> 8;
$baseColor = $variant & 0xFF;
$variant=$variant >> 8;
$patternColor = $variant & 0xFF;
//console.log($shape, $pattern,$baseColor,$patternColor);
var_dump([$shape, $pattern,$baseColor,$patternColor]);
}
calcValues(65535);
var_dump(0xFF);
?>
by mistake i deleted the "$variant= " .. this edited version gives me 255 255 0 0 (the same result for your javascript version ,using 65535 value)
here you have the complete guide of other functions https://www.php.net/manual/en/language.operators.bitwise.php
CodePudding user response:
IMO Constantin's answer is objectively best for OP's specific case. But...
While I maintain that you don't need >>>
equivalent for the given code, and >>
will work just fine, and have the further warning that using a >>>
equivalent on negative integer values across languages/systems with different integer/word sizes will have undefined behaviour, here is a function that replicates the behaviour of JS's >>>
operator.
// formatted decbin
function fdecbin($input) {
$out = decbin($input);
$len = ((int)ceil(strlen($out)/8))*8;
$out = str_pad($out, $len, '0', STR_PAD_LEFT);
return implode(' ', str_split($out, 8));
}
// zero-padded right bit shift
function zeroshift($input, $bits) {
if( $bits == 0 ) { return $input; }
$mask = PHP_INT_MAX >> ($bits - 1);
return $input >> $bits & $mask;
}
$i = -110;
var_dump(
fdecbin($i),
fdecbin($i>>2),
fdecbin(zeroshift($i, 2))
);
Output:
string(71) "11111111 11111111 11111111 11111111 11111111 11111111 11111111 10010010"
string(71) "11111111 11111111 11111111 11111111 11111111 11111111 11111111 11100100"
string(71) "00111111 11111111 11111111 11111111 11111111 11111111 11111111 11100100"
Again, please carefully consider what the code is actually doing before using an obscure, esoteric operator/operation like >>>
, or this code that replicates it.