How to write a constant time function to copy the most significant bit to all bits

假如想象 提交于 2019-12-03 13:19:50
Ilmari Karonen

How about:

#define uint8_msb_to_all_bits(x) (0xFF * ((x) >> 7))

or even better:

#define uint8_msb_to_all_bits(x) (-((x) >> 7))

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.

(Yes, negating an unsigned number is well defined in C.)

What about

- (x >> 7)

?

Only the MSB is retained and math negation is used to replicate it to all bits.

Given the declaration of your uint8_t:

uint8_t x = // MSB is either 1 or 0 if `x` depending on the signed value of `x`

A cheat that assumes 2's complement for signed integers:

return (((uint16_t)(int8_t)x) >> 8) & 0xff;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!