【问题标题】:Bitwise operation and arrow function return statement按位运算和箭头函数返回语句
【发布时间】:2022-04-25 02:31:45
【问题描述】:

我有一个字节,我想将剩下的第一个位增加 1(上下文是一个小的康威生命游戏)。

示例:11 是0000 1011

  1. 我想增加101
  2. 5 + 1 = 6 是110
  3. 将第一位重置为初始状态
  4. 字节现在是0000 1101,即13

    问题:

    • 有没有办法让addNeighbour 继续作为空白方法(我找不到方法不是返回num)?
    • 有没有更好的方法来执行addNeighbour 操作:

    const getBinaryRepresentation = (number) => {
        let str = \"\";
        for (let i = 7; i >= 0; i--) {
            ((number & (1 << i)) != 0) ? str += \"1\" : str += \"0\";
        }
        console.log(str)
    }
    
    let num = 5; 
    getBinaryRepresentation(num) // 0000 0101
    const addNeighbour = (num) => {
        const isAlive = num & 1;
        const neighbours = num >> 1;
    
        num = (neighbours + 1) << 1;
        if (isAlive === 1) num |= (1 << 0)
        return num;
    }
    num = addNeighbour(num);
    getBinaryRepresentation(num) // 0000 0111
  • 如果你删除 return num 它不会返回任何东西,也就是返回 void ...
  • 是的,但num的实际值不受影响,getBinaryRepresentation(num) 将返回 0000 0101
  • “第一位”是指 LSB?
  • @Bergi 完全!

标签: javascript bitwise-operators bit-shift arrow-functions


【解决方案1】:

有没有办法让addNeighbour 继续作为 void 方法(我找不到不返回num 的方法)?

不可以。如果您不返回结果,则无法将其分配回num。并且您不能传递对函数应该从中读取和存储的let num(或任何其他)变量的引用。

有没有更好的方法来执行addNeighbour 操作

是的。在第二个最低有效位位置添加1 与在最低有效位添加2 相同。将您的代码替换为

num += 2;

换个说法,

  (((num >> 1) + 1) << 1) | (num & 1)
≡ (((num >> 1) << 1) + (1 << 1)) | (num & 1)
≡ ((num & ~1) + (1 << 1)) | (num & 1)
≡ ((num & ~1) | (num & 1)) + (1 << 1)
≡ num + (1 << 1)

【讨论】:

  • 这会触发我的 LISP ptsd ...
【解决方案2】:

由于您不能在 javascript 中的简单值上使用 byRef,因此您不能返回 void 并在函数之外更改变量。

不过,您可以通过重用变量来优化函数:

const getBinaryRepresentation = (number) => {
  return console.log(number.toString(2).padStart(8, 0));
}

let num = 5;
getBinaryRepresentation(num) // 0000 0101
const addNeighbour = (num) => {
    const isAlive = num & 1;
    num >>= 1;
    num = (num + 1) << 1;
    return num | isAlive;
}
num = addNeighbour(num);
getBinaryRepresentation(num) // 0000 0111

【讨论】:

  • 确实更优雅,但像 Bergi 建议的那样添加 +2 似乎更适合我的用例。
  • 是的。最简单的解决方案往往是最好的解决方案......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-30
  • 1970-01-01
  • 2021-06-24
  • 2019-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多