如何简化这个"clear multiple bits at once"函数?
How to simplify this "clear multiple bits at once" function?
我终于通过反复试验弄清楚如何清除整数上的多个位:
const getNumberOfBitsInUint8 = function(i8) {
let i = 0
while (i8) {
i++
i8 >>= 1
}
return i
}
const write = function(n, i, x) {
let o = 0xff // 0b11111111
let c = getNumberOfBitsInUint8(x)
let j = 8 - i // right side start
let k = j - c // right side remaining
let h = c + i
let a = x << k // set bits
let b = a ^ o // set bits flip
let d = o >> h // mask right
let q = d ^ b //
let m = o >> j // mask left
let s = m << j
let t = s ^ q // clear bits!
let w = n | a // set the set bits
let z = w & ~t // perform some magic
return z
}
write
函数采用整数 n
、要写入位的索引 i
以及位值 x
。
有什么办法可以简化这个功能,去掉一些步骤吗? (不只是在一行中组合多个操作)?
一种可能是先清除相关部分,然后将位复制进去:
return (n & ~((0xff << (8 - c)) >> i)) | (x << (8 - c - i))
假设左移限制为 8 位,因此高位消失。另一种是使用异或来查找要更改的位:
return n ^ ((((n >> (8 - c - i)) ^ x) << (8 - c)) >> i)
我终于通过反复试验弄清楚如何清除整数上的多个位:
const getNumberOfBitsInUint8 = function(i8) {
let i = 0
while (i8) {
i++
i8 >>= 1
}
return i
}
const write = function(n, i, x) {
let o = 0xff // 0b11111111
let c = getNumberOfBitsInUint8(x)
let j = 8 - i // right side start
let k = j - c // right side remaining
let h = c + i
let a = x << k // set bits
let b = a ^ o // set bits flip
let d = o >> h // mask right
let q = d ^ b //
let m = o >> j // mask left
let s = m << j
let t = s ^ q // clear bits!
let w = n | a // set the set bits
let z = w & ~t // perform some magic
return z
}
write
函数采用整数 n
、要写入位的索引 i
以及位值 x
。
有什么办法可以简化这个功能,去掉一些步骤吗? (不只是在一行中组合多个操作)?
一种可能是先清除相关部分,然后将位复制进去:
return (n & ~((0xff << (8 - c)) >> i)) | (x << (8 - c - i))
假设左移限制为 8 位,因此高位消失。另一种是使用异或来查找要更改的位:
return n ^ ((((n >> (8 - c - i)) ^ x) << (8 - c)) >> i)