Search code examples
javascriptbinary-operators

How to achieve the output with binary operators?


I have three variables and trying to get the result using only binary operators. But somehow it does not work.

This does not work:

const var1 = 0x4C44
const var2 = 3
const var3 = 1

const result = (var1 << 32) + (var2 << 16) + var3

console.log(result.toString(16))

This is what I try to get:

const var1 = 0x4C44
const var2 = 3
const var3 = 1

const result = 0x4C4400030001

console.log(result.toString(16))

can anyone please point me in the right direction?


Solution

  • The << operator converts the number into a signed 32-bit integer. See https://262.ecma-international.org/9.0/#sec-left-shift-operator

    This means you get an overflow and strange results when you shift your number beyond 2^31.

    console.log(0x4C44 << 19)   //  1646264320
    console.log(0x4C44 << 20)   // -1002438656
    
    console.log((2**31)-1 << 0) //  2147483647
    console.log((2**31)   << 0) // -2147483648

    Use Javascript bigints instead (ECMAscript 2020 onwards):

    const var1 = 0x4C44n
    const var2 = 3n
    const var3 = 1n
    
    const result = (var1 << 32n) + (var2 << 16n) + var3
    
    console.log(result.toString(16))