Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

This example illustrates a problem with number shifting #272

Open
wollbit opened this issue Jul 13, 2022 · 0 comments
Open

This example illustrates a problem with number shifting #272

wollbit opened this issue Jul 13, 2022 · 0 comments
Labels
new-example A proposal of the new example

Comments

@wollbit
Copy link

wollbit commented Jul 13, 2022

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

@wollbit wollbit added the new-example A proposal of the new example label Jul 13, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
new-example A proposal of the new example
Projects
None yet
Development

No branches or pull requests

1 participant