简体   繁体   中英

how to concatenate bits in javascript?

I want to concatenate the bits of two number values like this:

+---------+---------+---------+-----------------+
|         |  val1   |  val2   | concatenate val |
+---------+---------+---------+-----------------+
| decimal | 18      | 16      | 592             |
| hexa    | 0x12    | 0x10    | 0x250           |
| binary  | 0b10010 | 0b10000 | 0b1001010000    |
+---------+---------+---------+-----------------+

I have try to just concatenate with + like that:

const test = 0b10010, test1 = 0b10000
console.log(test+test1)//return 34

It does not concatenate the values but adds them together.

You could shift the first value by the bitwise length of the second value before adding.

 const add = (a, b) => (a << Math.ceil(Math.log2(b)) + 1) + b; test = 0b10010, test1 = 0b10000, console.log(add(test, test1)); //

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