gauravds
gauravds

Reputation: 3011

javascript int64 to int32 using bitwise having issue

// javascript/node.js
unSignInt32Max = Math.pow(2, 32) - 1; // 4294967295 =>0xffffffff

x = unSignInt32Max + 3; // 4294967298 => 0x1_00000002

a = (x & 0xffffffff00000000) >> 32; // EXPECTING: 1 => 0x1; but got 0 => 0x0
b = x & 0xffffffff; // expectation full fill 2 => 0x2

y = (a << 32) | b; // EXPECTING: 4294967298 => 0x1_00000002; but got 2 => 0x2

console.log('x:', x, '0x' + x.toString(16));
console.log('a:', a, '0x' + a.toString(16));
console.log('b:', b, '0x' + b.toString(16));
console.log('y:', y, '0x' + y.toString(16));
console.log('result:', x == y);

Output:Javascript/node.js

x: 4294967298 0x100000002
a: 0 0x0
b: 2 0x2
y: 2 0x2
result: false

Why a = (x & 0xffffffff00000000) >> 32; result is not 1 instead of 0

While other languages like ruby has the same code and results as expected:

#ruby
unSignInt32Max = 2**32 - 1; # 4294967295 =>0xffffffff

x = unSignInt32Max + 3; # 4294967298 => 0x1_00000002

a = (x & 0xffffffff00000000) >> 32; # expectation full fill 1 => 0x1
b = x & 0xffffffff; # expectation full fill 2 => 0x2

y = (a << 32) | b; # expectation full fill 4294967298 => 0x1_00000002

puts "x:#{x}, 0x#{x.to_s(16)}"
puts "a:#{a}, 0x#{a.to_s(16)}"
puts "b:#{b}, 0x#{b.to_s(16)}"
puts "y:#{y}, 0x#{y.to_s(16)}"
puts "result #{x == y}"

Output:Ruby

x:4294967298, 0x100000002
a:1, 0x1
b:2, 0x2
y:4294967298, 0x100000002
result true

Upvotes: 1

Views: 245

Answers (1)

gauravds
gauravds

Reputation: 3011

Yes, got the solution. Thanks @ASDFGerte.

It's bigInt problem and improved working version of JS/node.js is:

unSignInt32Max = Math.pow(2, 32) - 1; // 4294967295 =>0xffffffff

x = BigInt(unSignInt32Max + 3); // 4294967298 => 0x1_00000002

a = (x & 0xffffffff00000000n) >> 32n; // expectation full fill 1n => 0x1
b = parseInt(x); // expectation full fill 2 => 0x2

y = (a << 32n) | BigInt(b); // EXPECTING: 4294967298 => 0x1_00000002; but got 2 => 0x2

console.log('x:', x, '0x' + x.toString(16));
console.log('a:', a, '0x' + a.toString(16));
console.log('b:', b, '0x' + b.toString(16));
console.log('y:', y, '0x' + y.toString(16));
console.log('result:', x == y);

Output: Javascript

x: 4294967298n 0x100000002
a: 1n 0x1
b: 4294967298 0x100000002
y: 4294967298n 0x100000002
result: true

Upvotes: 1

Related Questions