如何写一个恒定时间函数来最显著位复制到所有的位 [英] How to write a constant time function to copy the most significant bit to all bits
问题描述
我想编写一个函数,在C,这需要 uint8_t有
的MSB,如果它的设置,返回 0xFF的
如果没有 0×00
。总之,它返回其中所有的位被设置为相同的值作为MSB的整数。
I'd like to write a function, in C, which takes the MSB of uint8_t
, and if it's set, returns 0xFF
and if not 0x00
. In short, which returns an integer where all the bits are set to the same value as the MSB.
但我想这样做在一个完全固定的时间的方式,没有分支,没有数组偏移,这是保证始终触摸相同的比特数只是数学运算。理想情况下,没有任何不确定的行为。如何才能做到这一点?
But I'd like to do it in a completely constant time way, no branches, no array offsets, just mathematical operations which are guaranteed to always touch the same number of bits. And ideally, without any undefined behavior. How can this be done?
推荐答案
如何
#define uint8_msb_to_all_bits(x) (0xFF * ((x) >> 7))
甚至更好:
#define uint8_msb_to_all_bits(x) (-((x) >> 7))
在这部分都工作是,如果 X
是一个8位无符号整数,那么 X>> 7
如果是1的MSB X
设置,否则为0。所有剩下然后映射1为0xFF,这是可以做到既通过乘法,或者,在这种特定的情况下,简单地通过否定的数目。
The way these both work is that, if x
is an 8-bit unsigned integer, then x >> 7
is 1 if the MSB of x
is set, and 0 otherwise. All that remains is then mapping 1 to 0xFF, which can be done either by multiplication, or, in this particular case, simply by negating the number.
(是的,否定一个无符号数很好用C 定义。)
这篇关于如何写一个恒定时间函数来最显著位复制到所有的位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!