Stweet
Stweet

Reputation: 713

javascript decimal (16 lower bits) to decimal

Sorry but i'm not good at bit conversion. I need to convert decimal -> decimal by lower 16 bit, as this sample.

1:16777237 decimal = 1000015 hex
2:16 lower bits = 0015 hex (each digit in hexadecimal is 4 bits)
3: 0015 hex = 21 decimal  (21 is the result i need)

Using

(16777237).toString(16);

i can get the 1000015 hex, my question is how, i get the lower bits as im, not that strong in bits. etc. the bedst way to get the result.

Upvotes: 1

Views: 321

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386883

You could apply a bitmask with 11111111111111112 and get the result with bitwise AND.

              base 2             base 10   base 16
    -------------------------   --------   -------
    1000000000000000000010101   16777237   1000015
&   0000000001111111111111111      65535      ffff
-----------------------------   --------   -------
    0000000000000000000010101         21        15

console.log(16777237 & ((1 << 16) - 1));

Another solution could be, just to use the remainder operator % with 216.

console.log(16777237 % (1 << 16));

Upvotes: 3

Related Questions