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

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -