I'm trying to convert parts of a python script into php. I know most of it, but I've run into something to do with bitshifting (i think?) which I don't have much experience in even in PHP! Can somebody translate this python function into php please?
def setBit(value, position, on):
if on:
mask = 1 << position
return (value | mask)
else:
mask = ~(1 << position)
return (value & mask)
asked Jan 20, 2012 at 1:40
Landon
4,1183 gold badges34 silver badges43 bronze badges
2 Answers 2
function setBit($value, $position, $on = true) {
if($on) {
return $value | (1 << $position);
}
return $value & ~(1 << $position);
}
Sign up to request clarification or add additional context in comments.
1 Comment
Landon
wow, that's just embarrassing, it's like a carbon copy of the python function! I guess I've just never used the << operator before, anyway, thanks!
function SetBit ($value, $position, $on) {
if ($on) return ($value|(1<<$position));
return ($value&(~(1<<$position)));
}
answered Jan 20, 2012 at 1:45
Robert Allan Hennigan Leahy
6,6181 gold badge32 silver badges47 bronze badges
2 Comments
DaveRandom
This could be reduced to one line, if you're going to take that approach:
return ($on) ? $value | (1 << $position) : $value & ~(1 << $position);Robert Allan Hennigan Leahy
I love that little ternary operator, so good at making code more compact. My goal wasn't actually one line, my goal was to eliminate intermediary variables. I hate assigning anything to a variable that isn't going to be used more than once...a hang up of mine...
default