位運(yùn)算符在 JS 中的妙用

原文地址:http://interview.poetries.top/
按位與(AND)&
將數(shù)字轉(zhuǎn)換成二進(jìn)制,然后進(jìn)行與操作,再轉(zhuǎn)換回十進(jìn)制
//?1?的二進(jìn)制表示為?00000000?00000000?00000000?00000001
//?3?的二進(jìn)制表示為?00000000?00000000?00000000?00000011
//?--------------------------------------------------
//?1?的二進(jìn)制表示為?00000000?00000000?00000000?00000001
console.log(1?&?3)?//?1
按位或(OR)|
將數(shù)字轉(zhuǎn)換為二進(jìn)制,然后進(jìn)行或操作,再轉(zhuǎn)換回十進(jìn)制
//?1?的二進(jìn)制表示為?00000000?00000000?00000000?00000001
//?3?的二進(jìn)制表示為?00000000?00000000?00000000?00000011
//?--------------------------------------------------
//?3?的二進(jìn)制表示為?00000000?00000000?00000000?00000011
console.log(1?|?3)?//?3
按位異或(XOR)^
將數(shù)字轉(zhuǎn)換為二進(jìn)制,然后進(jìn)行異或操作,再轉(zhuǎn)換回十進(jìn)制
//?1?的二進(jìn)制表示為?00000000?00000000?00000000?00000001
//?3?的二進(jìn)制表示為?00000000?00000000?00000000?00000011
//?--------------------------------------------------
//?2?的二進(jìn)制表示為?00000000?00000000?00000000?00000010
console.log(1?^?3)?//?2
按位非(NOT)~
將數(shù)字轉(zhuǎn)換為二進(jìn)制,然后進(jìn)行非操作,再轉(zhuǎn)換回十進(jìn)制,也就求二進(jìn)制的反碼
//?1?反碼二進(jìn)制表示為?11111111?11111111?11111111?11111110
//?由于第一位(符號(hào)位)是1,所以這個(gè)數(shù)是負(fù)數(shù)。JavaScript 內(nèi)部采用補(bǔ)碼形式表示負(fù)數(shù),即需要將這個(gè)數(shù)減去 1,再去一次反,然后加上負(fù)號(hào)才能得到這個(gè)負(fù)數(shù)對(duì)應(yīng)的十進(jìn)制數(shù)值
//?1?的反碼減一表示為?11111111?11111111?11111111?11111101
//?取反?????????????00000000?00000000?00000000?00000010
//?表示為?-2
console.log(~1)?//?-2
左移(Left shift)<<
將數(shù)字轉(zhuǎn)換成二進(jìn)制,然后丟棄高位,低位補(bǔ)0
//?1?的二進(jìn)制表示為?00000000?00000000?00000000?00000001
//?2?的二進(jìn)制表示為?00000000?00000000?00000000?00000010
console.log(1?<1)?//?2
有符號(hào)右移 >>
將數(shù)字轉(zhuǎn)成二進(jìn)制,然后丟棄低位,拷貝最左側(cè)的位以填充左側(cè)
//?1?的二進(jìn)制表示為?00000000?00000000?00000000?00000001
//?0?的二進(jìn)制表示為?00000000?00000000?00000000?00000000
console.log(1?>>?1)?//?0
無符號(hào)右移 >>>
將數(shù)字轉(zhuǎn)成二進(jìn)制,然后丟棄低位,左側(cè)補(bǔ)0,因此總是非負(fù)數(shù)。
對(duì)于非負(fù)數(shù),有符號(hào)右移和無符號(hào)右移結(jié)果總是相等。
位運(yùn)算符在 JS 中的妙用
判斷奇偶
//?偶數(shù)?&?1?=?0
//?奇數(shù)?&?1?=?1
console.log(2?&?1)?//?0
console.log(3?&?1)?//?1
取整
console.log(~~6.83)?//?6
console.log(6.83?>>?0)?//?6
console.log(6.83?<0)?//?6
console.log(6.83?|?0)?//?6
//?不可對(duì)負(fù)數(shù)取整
console.log(6.83?>>>?0)?//?6
交換值
var?a?=?6
var?b?=?8
a?^=?b
b?^=?a
a?^=?b
console.log(a)?//?8
console.log(b)?//?6
RGB 值和16 進(jìn)制顏色值轉(zhuǎn)換
function?hexToRGB(hex:?string):?string{
??const?hexx?=?hex.replace('#',?'0x')
??const?r?=?hexx?>>?16
??const?g?=?hexx?>>?8?&?0xff
??const?b?=?hexx?&?0xff
??return?`rgb(${r},?${g},?$)`
}
function?RGBToHex(rgb:?string):?string{
??const?rgbArr?=?rgb.split(/[^\d]+/)
??const?color?=?rgbArr[1]?|?rgbArr[2]?<8?|?rgbArr[3]
??return?`#${color.toString(16)}`
}
??愛心三連擊 1.看到這里了就點(diǎn)個(gè)在看支持下吧,你的「點(diǎn)贊,在看」是我創(chuàng)作的動(dòng)力。
2.關(guān)注公眾號(hào)
程序員成長指北,回復(fù)「1」加入高級(jí)前端交流群!「在這里有好多 前端?開發(fā)者,會(huì)討論?前端 Node 知識(shí),互相學(xué)習(xí)」!3.也可添加微信【ikoala520】,一起成長。
“在看轉(zhuǎn)發(fā)”是最大的支持
評(píng)論
圖片
表情
