【JS】832- 位運(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
//?由于第一位(符號位)是1,所以這個數(shù)是負(fù)數(shù)。JavaScript 內(nèi)部采用補(bǔ)碼形式表示負(fù)數(shù),即需要將這個數(shù)減去 1,再去一次反,然后加上負(fù)號才能得到這個負(fù)數(shù)對應(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
有符號右移 >>
將數(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
無符號右移 >>>
將數(shù)字轉(zhuǎn)成二進(jìn)制,然后丟棄低位,左側(cè)補(bǔ)0,因此總是非負(fù)數(shù)。
對于非負(fù)數(shù),有符號右移和無符號右移結(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
//?不可對負(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},?${b})`
}
function?RGBToHex(rgb:?string):?string{
??const?rgbArr?=?rgb.split(/[^\d]+/)
??const?color?=?rgbArr[1]?|?rgbArr[2]?<8?|?rgbArr[3]
??return?`#${color.toString(16)}`
}

回復(fù)“加群”與大佬們一起交流學(xué)習(xí)~
點(diǎn)擊“閱讀原文”查看 100+ 篇原創(chuàng)文章
評論
圖片
表情
