Search code examples
javascriptbit-manipulationbitwise-operators

What does OR 0x80 do?


In Bitwise operation, what does | 0x80 do? I know (& 0xFF) is convert value to 8 bit integer but how about (| 0x80) ? I have the following code:

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
  }

Can anyone explain that for me?


Solution

  • 0x... means that what comes next is an hexadecimal number. 0x80 is the hexadecimal representation of the number 128. In binary, this equals 10000000.

    The | character is the bitwise or operator. Suppose you have a 8-bit number:

    a = xxxxxxxx
    

    with x being either a 0 or a 1. Now, masking this number with 0x80 means:

    xxxxxxxx | 10000000 = 1xxxxxxx
    

    So it basically means you will have a 1 for your leftmost significant bit, while keeping all the other bits the same.

    Now, in your code you use this mask in the line:

    const shifted = (ubyte >> 1) | mask
    

    What this does is takes the number ubyte:

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

    It shifts it right by onw digit:

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

    Now it masks this number with your mask. When the mask is 128, the result is:

    (ubyte >> 1) | 10000000 = 1xxxxxxx
    

    So you will have a 1 as your most significant bit, and the other bits are unchanged.