1

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)    

2 Answers 2

7
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

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!
4
function SetBit ($value, $position, $on) {

    if ($on) return ($value|(1<<$position));

    return ($value&(~(1<<$position)));

}

2 Comments

This could be reduced to one line, if you're going to take that approach: return ($on) ? $value | (1 << $position) : $value & ~(1 << $position);
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...

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.