【问题标题】:how to concatenate bits in javascript?如何在javascript中连接位?
【发布时间】:2021-05-29 13:53:16
【问题描述】:

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

+---------+---------+---------+-----------------+
|         |  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

它不会连接这些值,而是将它们相加。

【问题讨论】:

  • parseInt(test.toString(2) + test1.toString(2), 2)
  • 它也可以,但是将数字转换为字符串连接很奇怪
  • 这到底应该做什么?像这样“连接”二进制数是不寻常的,因为它们在内部存储为 32 位整数。所以0b10010其实就是0b00000000000000000000000000010010
  • 我尝试使用套接字协议并将接收到的字节存储到 Uinit8Array 但在协议框架中有一个以 6 字节编码的 mac 地址,并且我需要连接存储此地址帧的一些字节。

标签: javascript casting binary


【解决方案1】:

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

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

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

【讨论】:

  • 它完全可以工作,但是这个函数在做什么?
  • @MrSolarius “developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • 感谢您的回复和信息^^
  • @MrSolarius 而不是Math.ceil(Math.log2(b)) + 1,您可以使用更简单的32-Math.clz32(b)...
猜你喜欢
  • 1970-01-01
  • 2011-07-25
  • 1970-01-01
  • 1970-01-01
  • 2018-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-02
相关资源
最近更新 更多