mjekov
mjekov

Reputation: 682

Adding two hex numbers javascript with bit shift

I am trying to add two numbers in JavaScript, represented in hexadecimal base, in the following way:

var a = 0x0028 << 16 + 0x0010;

and what I expect to get is 0x00280010. Unfortunately JavaScript makes a equals 40, (which of course is 0x0028). If I shift the bits without adding 0x0010, everything works fine, I get 2621440 for a, which is 0x280000. Why adding 0x0010 yields such results for a. I am not that good at this kind of arithmetic, am I doing or expecting something wrong? Thank you all in advance :)

Upvotes: 1

Views: 4293

Answers (2)

Mark Fisher
Mark Fisher

Reputation: 9886

Put brackets around the shift as it has lower precedence than the plus (see this page)

a = (0x0028 << 16) + 0x0010
> 2621456

Upvotes: 1

BatScream
BatScream

Reputation: 19700

use brackets: + has higher precedence over <<.

var a = (0x0028 << 16) + 0x0010 // note the brackets.

Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

Upvotes: 4

Related Questions