mirror of
https://github.com/trekhleb/javascript-algorithms.git
synced 2025-12-08 19:06:00 +00:00
17 lines
473 B
JavaScript
17 lines
473 B
JavaScript
/**
|
|
* @param {number} number
|
|
* @param {number} bitPosition - zero based.
|
|
* @param {number} bitValue - 0 or 1.
|
|
* @return {number}
|
|
*/
|
|
export default function updateBit(number, bitPosition, bitValue) {
|
|
// Normalized bit value.
|
|
const bitValueNormalized = bitValue ? 1 : 0;
|
|
|
|
// Init clear mask.
|
|
const clearMask = ~(1 << bitPosition);
|
|
|
|
// Clear bit value and then set it up to required value.
|
|
return (number & clearMask) | (bitValueNormalized << bitPosition);
|
|
}
|