I have a byte, and I want to increment bits left to the first bit by 1 (the context is a small Conway's Game of Life).
Example: 11 is 0000 1011
:
101
110
0000 1101
which is 13Questions:
addNeighbour
proceed as a void method (I couldn't find a way to not return num
)?addNeighbour
operations :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
Is there a way to make
addNeighbour
proceed as a void method (I couldn't find a way to not returnnum
)?
No. If you don't return the result, you cannot assign it back to num
. And you cannot pass a reference to the let num
(or any other) variable that the function should read from and store into.
Is there a better way to perform
addNeighbour
operations
Yes. Adding 1
at the second-least significant bit position is just the same as adding 2
at the least signification position. Replace your code with
num += 2;
Put in other terms,
(((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)