用按位运算替换最低有效位
用提供的位替换字节的最低有效位的最佳方法是什么?
我知道如何检查和比较最后一位(例如使用 posix ffs() 函数),但我想知道是否有性能更好的解决方案,而不检查替换位是 0 还是 1。
该示例是用 python 编写的作为伪代码,但我将在 C 中实现工作算法:
>>> bin(0b1) # bit is '0b1'
>>> bin(128) # byte is '0b10000000'
>>> bin(129) # byte is '0b10000001'
>>> bin(128 OPERATOR 0b1) # Replace LSB with 1
'0b10000001'
>>> bin(128 OPERATOR 0b0) # Keep LSB at 0
'0b10000000'
>>> bin(129 OPERATOR 0b1) # Keep LSB at 1
'0b10000001'
>>> bin(129 OPERATOR 0b0) # Replace LSB with 0
'0b10000000'
显然运算符可以是一组操作,但我正在寻找最佳(最快)方法。
What is a optimal way to replace the Least Significant Bit of a byte, with a provided bit?
I know how to do checking and comparing last bit (using for example posix ffs() function), but I want to know if there are solutions with better performance, without checking if replacing bit is 0 or 1.
The example is written in python as pseudocode, but I will implement the working algorithm in C:
>>> bin(0b1) # bit is '0b1'
>>> bin(128) # byte is '0b10000000'
>>> bin(129) # byte is '0b10000001'
>>> bin(128 OPERATOR 0b1) # Replace LSB with 1
'0b10000001'
>>> bin(128 OPERATOR 0b0) # Keep LSB at 0
'0b10000000'
>>> bin(129 OPERATOR 0b1) # Keep LSB at 1
'0b10000001'
>>> bin(129 OPERATOR 0b0) # Replace LSB with 0
'0b10000000'
Obviously operator can be a set of operations, but I'm looking for the optimal (fastest) method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
n & ~1
将n
的最低有效位替换为零;n | 1
,有一个。要将 LSB 替换为
b
(其中b
可以是 0 或 1),您可以使用(n & ~1) | b。
要将第
k
位替换为b
(其中k=0
代表 LSB):(n & ~( 1 << k))| (b << k)
。n & ~1
replaces the least significant bit ofn
with zero;n | 1
, with one.To replace the LSB with
b
, whereb
can be either 0 or 1, you can use(n & ~1) | b
.To replace the
k
-th bit withb
(wherek=0
stands for the LSB):(n & ~(1 << k)) | (b << k)
.您可能还想检查您是采用大端还是小端架构。在大端机器中,最低有效字节位于最高地址。
检查字节序
在 Python 中,您可以通过sys.byteorder
。在 C 中,您需要自己检查字节序,使用 union 进行破解很容易。
You also might want to check if you are on big endian or little endian architecture. In big endian machines the least significant byte is at the highest address.
In Python you can check endian-ness by
sys.byteorder
In C you need to check endian-ness on your own, hack using unions is easy to do.