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
:
- I want to increment
101
- 5 1 = 6 is
110
- reset the first bit to initial state
- the byte is now
0000 1101
which is 13
Questions:
- Is there a way to make
addNeighbour
proceed as a void method (I couldn't find a way to not returnnum
)? - Is there a better way to perform
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
CodePudding user response:
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)
CodePudding user response:
Since you can't have byRef
on simple values in javascript you can't return void and change variable outside of the function.
You could optimize a little the function though, by reusing variables:
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