javascript - 如何在javascript中连接位?

标签 javascript casting binary

我想像这样连接两个数值的位:

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

我尝试像这样与 + 连接:

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

它不会连接值,而是将它们加在一起。

最佳答案

在添加之前,您可以将第一个值移动第二个值的按位长度。

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

console.log(add(test, test1)); //

关于javascript - 如何在javascript中连接位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66398429/

相关文章:

javascript - bootstrap-angular 模态对话框 : can not return value from select

javascript - 其他 js 事件移动设备内的 JS 事件

javascript - 模态 Bootstrap 用户输入

python - 解析 Yann LeCun 的 MNIST IDX 文件格式

c# - 在 .NET 中将 Int 数组写入 Stream

javascript - jsonpath : How to access a key in current object when the key name is having "hyphen" in it?

c - 将 C 指针打印为 %i 和 %u

c++ - sqrt(int_value + 0.0) -- 它有目的吗?

c++ - 如何将基类指针数组转换为派生类

javascript - 在 JavaScript 中将 Base64 字符串分配给图像