denysdovhan / wtfjs

🤪 A list of funny and tricky JavaScript examples
http://bit.ly/wtfjavascript
Do What The F*ck You Want To Public License
35.07k stars 2.55k forks source link

This example illustrates a problem with number shifting #272

Open wollbit opened 2 years ago

wollbit commented 2 years ago

This example illustrates a problem with number shifting.

Code for testing:

// In the first example, a hexadecimal number is output binary as a string. However, this also works decimal! let y = 0; let x = 0x00000001; // Bit 1 console.log('1) ' + x.toString(2) ); // Result: 1) 1

// In the second example the 32nd bit is set to 1 x = 0x80000000; // Bit 32 console.log('2) ' + x.toString(2) ); // Result: 2) 10000000000000000000000000000000

// In the second example the 30nd bit is set to 1 x = 0x20000000; // Bit 30 console.log('3) ' + x.toString(2) ); // Result: 3) 100000000000000000000000000000

// In this example we shift the 30th bit one place to the left x = 0x20000000; // Bit 30 y = x << 1; console.log('4) ' + y.toString(2) ); // Result: 4) 1000000000000000000000000000000

// Up to here everything works normally

// The next example returns an unexpected value. // Here the 30th bit is shifted two bits to the left to the position of the 32nd bit. The result is suddenly negative. x = 0x20000000; // Bit 30 y = x << 2; console.log('5) ' + y.toString(2) ); // Result: 5) -10000000000000000000000000000000

// This is how to get around the problem x = 0x40000000; // Bit 31 x *= 2; console.log('6) ' + x.toString(2) ); // Result: 6) 10000000000000000000000000000000