Shift Operator only working when shifting until 16 digits

1

I have been trying to find the answer all morning, so happy to close this question if it is a duplicate. I am tying to get the first 2 digits of a hex number that has 8 digits.

I understand that >> moves x bits to the right. So doing 0b10 >> 1 ends up in 0b01

All works for the last 6 digits. The last 2 hex numbers:

0x000000FF >> 0 // 255
0b00000000000000000000000011111111 >> 0 == 0b00000000000000000000000011111111 // == 255

The 3th and 4th hex digit from the right:

0x0000ff00 >> 8 // 255
0b00000000000000001111111100000000 >> 8 == 0b00000000000000000000000011111111 // == 255

The 5th and the 6th hex from right:

0x00ff0000 >> 16
0b00000000111111110000000000000000 >> 16 == 0b00000000000000000000000011111111 // == 255

Trying to get the 7th and 8th hex number from the rigth, or the first 2 from the left should moving all bits 24 places to the right:

0xff000000 >> 24
0b11111111000000000000000000000000 >> 24 => Should be 255, but it is -1

How can I get 0b11111111000000000000000000000000 to become 255?

javascript
binary
hex
shift
asked on Stack Overflow Aug 18, 2020 by regina_fallangi • edited Aug 18, 2020 by regina_fallangi

1 Answer

3

The answer is simple, the >> operator is a signed shift operator, so instead you would simply use an unsigned version >>>:

console.log(0xff000000 >> 24)
console.log(0xff000000 >>> 24)

answered on Stack Overflow Aug 18, 2020 by Krzysztof Krzeszewski • edited Aug 18, 2020 by T.J. Crowder

User contributions licensed under CC BY-SA 3.0