OR 0x80 有什么作用?

What does OR 0x80 do?

在位运算中,有什么用 | 0x80呢?我知道 (& 0xFF) 是将值转换为 8 位整数,但是 (| 0x80) 呢? 我有以下代码:

const buf = createHash('sha256').update('test').digest()

  for (let i = 0; i < n; i++) {
    const ubyte = buf.readUInt8(i)
    const shifted = (ubyte >> 1) | mask
    destBuf.writeUInt8(shifted, i)


    mask = (ubyte & 1) * 0x80 // mask is 0 or 128
  }

谁能帮我解释一下?

它将两个参与号码的位与逻辑“或”结合起来:

const b= 0x7;

function tst(a,b){
  console.log(a.toString(2).padStart(8)+" first number: "+a)
  console.log(b.toString(2).padStart(8)+" second number: "+b)
  console.log((a | b).toString(2).padStart(8)+" bitwise overlay: "+(a|b))
  console.log("----")    
}

[0x80,0x6A,0x70,0x8f].forEach(a=>tst(a,b))

0x...表示接下来是十六进制数。 0x80 是数字 128 的十六进制表示。在二进制中,这等于 10000000

|字符是按位或运算符。假设你有一个 8 位数:

a = xxxxxxxx

其中 x 是 01。现在,用 0x80 屏蔽这个数字意味着:

xxxxxxxx | 10000000 = 1xxxxxxx

所以这基本上意味着您的最左边的有效位将是 1,同时保持所有其他位相同。

现在,在您的代码中,您在行中使用此掩码:

const shifted = (ubyte >> 1) | mask

它所做的是获取数字 ubyte:

ubyte = xxxxxxxy // x and y can be either 1 or 0

它向右移动了一位:

ubyte >> 1 = zxxxxxxx // y gets lost, and z is a 0 if ubyte was unsigned.

现在它用你的面具掩盖了这个数字。当掩码为128时,结果为:

(ubyte >> 1) | 10000000 = 1xxxxxxx

所以你将有一个 1 作为你的最高有效位,其他位不变。