简体   繁体   English

如何连接 javascript 中的位?

[英]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)); //

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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