gpt4 book ai didi

c++ - "rounding"整数

转载 作者:太空宇宙 更新时间:2023-11-04 14:36:40 25 4
gpt4 key购买 nike

我正在努力摆脱函数中的 float 。

我有一个函数对 16 位整数值进行操作,该值是一个放大的 8 位值。然后将缩小的 8 位发送到输出。

我确定我解释得不好。像这样:

int8 spot_value = 21;  //arbitrary. just need a starting point
int16 running_value;

running_value = spot_value << 8; //multiply by 256 which is 5376
running_value += 154; //my upscaled value is now 5530
spot_value = running_value >> 8; //downscale again

如果我们使用 float ,我缩小后的值将是 21.6,我可以轻松地将其四舍五入为 22 并转换为 int8。但它会截断为我不想要的 21。

如果它是一个 float 但不将任何内容转换为 float (即使是暂时的),如果这样做是合适的,是否有一种方法可以将整数“四舍五入”?

这可能比我想象的要简单得多。

最佳答案

您可以将 1/2 添加到该值。在您的缩放系统中为 128。

int8 spot_value = 21;  //arbitrary. just need a starting point
int16 running_value;

running_value = spot_value << 8; //multiply by 256 which is 5376
running_value += 154; //my upscaled value is now 5530
spot_value = running_value + 128; //add an additional 1/2 for rounding
spot_value = spot_value >> 8; //downscale again

或者...

scale_shift = 8;
scale = 1 << scale_shift
round = scale >> 1;

int8 spot_value = 21; //arbitrary. just need a starting point
int16 running_value;

running_value = spot_value << scale_shift; //multiply by 256 which is 5376
running_value += 154; //my upscaled value is now 5530
spot_value = (running_value + round) >> scale_shift; //downscale again

或者基于 Dav 的回答的小技巧......

running_value = spot_value << scale_shift;  //multiply by 256 which is 5376
running_value += 154; //my upscaled value is now 5530
spot_value = (running_value >> 8) + ((running_value >> 7) & 1)

.

关于c++ - "rounding"整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1384348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com