// 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);Salida: Javascript/node.js
x: 4294967298 0x100000002 a: 0 0x0 b: 2 0x2 y: 2 0x2 result: false Por qué a = (x & 0xffffffff00000000) >> 32; el resultado no es 1 en lugar de 0
Mientras que otros lenguajes como ruby tienen el mismo código y resultados esperados:
#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}"Salida:Rubí
x:4294967298, 0x100000002 a:1, 0x1 b:2, 0x2 y:4294967298, 0x100000002 result trueSí, tengo la solución. Gracias @ASDFGerte.
Es un problema de bigInt y la versión de trabajo mejorada de JS/node.js es:
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);Salida: JavaScript
x: 4294967298n 0x100000002 a: 1n 0x1 b: 4294967298 0x100000002 y: 4294967298n 0x100000002 result: true