[英]Most efficient way to convert float 16ths to 4 bit integer in C
As part of an anti-aliasing routine I'm running on an STM32 (single precision FPU, if that matters), I'm looking to convert a float value 0 ≤ x < 1 to a 4 bit nibble representing opacity.作为抗锯齿例程的一部分,我在 STM32(单精度 FPU,如果重要的话)上运行,我希望将浮点值 0 ≤ x < 1 转换为表示不透明度的 4 位半字节。 Basically each LSB of the nibble corresponds to a 16th of the float, so 0 ≤ x < 0.0625 would be 0x0, 0.0625 ≤ x < 0.125 would be 0x1, so on.基本上,半字节的每个 LSB 对应于浮点数的第 16 位,因此 0 ≤ x < 0.0625 将是 0x0,0.0625 ≤ x < 0.125 将是 0x1,依此类推。 Are there any bit manipulation tricks I could use to make this operation fast/efficient?我可以使用任何位操作技巧来使此操作快速/高效吗?
For any floating-point value, x
, such that 0 <= x < 1
, the value y = x * 16
will give y <= 0 < 16
.对于任何浮点值x
,例如0 <= x < 1
,值y = x * 16
将给出y <= 0 < 16
。 Casting this float
value to an unsigned char
will set the lower nibble of that byte to the number of 16 th s.将此float
值转换为unsigned char
会将那个字节的低半字节设置为第 16位的数字。 Thus:因此:
float x = 0.51;
unsigned char b = (unsigned char)(x * 16);
Then b
will have the value 0x08
- representing eight sixteenths;然后b
的值为0x08
- 代表十六分之八; and likewise for any other (valid) value of x
.同样对于x
的任何其他(有效)值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.