简体   繁体   中英

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.

You could apply a bitmask with 1111111111111111 2 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 2 16 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM