binary - JavaScript set bits from the left -
i have number, example 128
. bit representation 10000000
. want set 3rd bit left have 10100000
(160
).
i thought with:
var foo = 128; foo = foo | 1 << 2;
but gives me 132
or 10000100
. set 3rd from right! how set left to 0 or 1?
this worked:
var foo = 128; foo = foo | foo >> 2
but if want turn on , off?
var foo = 128; var mask = foo >> 2; // flick bit on foo = foo | mask; // foo equals 160 // set bit 0 foo = foo & ~mask; // foo equals 128 again
Comments
Post a Comment