Created
January 3, 2022 11:48
-
-
Save sotnikov-link/22aece81702de29b4e239c4a30d82fe6 to your computer and use it in GitHub Desktop.
Переключить бит по индексу
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Переключить бит по индексу | |
*/ | |
function switchBit( | |
/** | |
* Числовое значение, в котором нужно переключить бит по индексу | |
* | |
* @type {number} | |
*/ | |
current, | |
/** | |
* Длина двоичного представления с ведущими нулями | |
* | |
* @type {number} | |
*/ | |
length, | |
/** | |
* Индекс бита | |
* | |
* @type {number} | |
*/ | |
index, | |
/** | |
* Значение «0» или «1», на которое будет переключен бит по указанному | |
* индексу. Если значение не указано, то бит будет переключен | |
* в противоположное значение. | |
* | |
* @type {0 | 1 | undefined} | |
*/ | |
value | |
) { | |
/** Текущее значение в двоичном виде */ | |
let currentBin = current.toString(2); | |
while (currentBin.length < length) { | |
currentBin = "0" + currentBin; | |
} | |
/** Следующее значение в двоичном виде */ | |
const nextBin = | |
currentBin.slice(0, index) + | |
(typeof value === "number" | |
? value | |
: currentBin[index] === "0" | |
? "1" | |
: "0") + | |
currentBin.slice(index + 1); | |
/** Результат */ | |
const result = parseInt(nextBin, 2); | |
console.log({ | |
current, | |
length, | |
index, | |
value, | |
currentBin, | |
nextBin, | |
result, | |
}); | |
return result; | |
} | |
// Примеры использования | |
console.log( | |
"Число 3 (10), представить в двоичным виде длиной в 16 знаков и переключить", | |
"последний бит по 15 индексу, будет 2 (10)", | |
switchBit(3, 16, 15) === 2 | |
); | |
console.log( | |
"В числе 100 (10), переключить 12 бит по индексу", | |
switchBit(100, 16, 16 - 4) === 108 | |
); | |
console.log( | |
"Без изменений, потому что указан переход к 0, который уже был", | |
switchBit(100, 16, 16 - 4, 0) === 100 | |
); | |
console.log( | |
"0000 0000 0000 0001 → 0000 0000 0000 1001", | |
switchBit(1, 16, 16 - 4) === 9 | |
); | |
console.log( | |
"0000 0000 0000 0001 → 0001 0000 0000 0001", | |
switchBit(1, 16, 3) === 4097 | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment