开发者

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?


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 a BigInteger library instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜