简体   繁体   English

在 C 中将 float 16ths 转换为 4 位整数的最有效方法

[英]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.

相关问题 将无符号16位整数存储到文件的最有效方法 - Most efficient way to store an unsigned 16-bit Integer to a file 将 16 位值转换为 8 位值的有效方法 - efficient way to convert 16 bit value to 8 bit value 在 C 的 integer 中找到最高设置位 (msb) 的最快/最有效的方法是什么? - What is the fastest/most efficient way to find the highest set bit (msb) in an integer in C? 将 2 个字节转换为有符号的 16 位整数的正确方法是什么? - What is the correct way to convert 2 bytes to a signed 16-bit integer? 如何将4个Modbus寄存器(每个16位)转换为C中的双浮点数? - How to convert 4 modbus registers (each 16 bit) to a double float in C? c-将char *数组转换为int和float的最有效方法是什么? - c - What is the most efficient way of converting char * array to int and float? 找到char变量中唯一&#39;1&#39;位的索引的最有效方法(在C中) - Most efficient way to find the index of the only '1' bit in a char variable (in C) C - 是否有更有效的方法将unsigned char数组的项“转换”为32位整数值? (共享内存?) - C - Is there a more efficient way to “convert” items of an unsigned char array to an 32bit integer value? (Shared memory?) 从预乘浮点RGBA转换为8位RGBA的有效方法? - Efficient way to convert from premultiplied float RGBA to 8-bit RGBA? 引用C中整数常量的最有效RAM方法 - Most RAM efficient way to reference integer constants in C
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM