arrays - 减少在 C 中按倍数计算所需的计算量
问题描述
x
我试图用uint8_t
c 数组中的倍数来计数。这样,每当倍数x
溢出 256 限制时,它就会在下一个类别中增加,类似于时钟的指针或二进制计数。如果x
是 80,一个例子可能是:
(0, 0, 0) -> 0
(80, 0, 0) -> 1
(160, 0, 0) -> 2
(240, 0, 0) -> 3
(0, 80, 0) -> 4
...
到目前为止,我已经能够使用这些方程组来实现它:
uint16_t get_max(uint8_t bound){
return (255+bound)/bound;
}
static void bind(uint32_t val, uint8_t bound, uint8_t rgb[3]){
uint16_t max = bound*get_max(bound);
rgb[0] = (val*bound)%max;
rgb[1] = (((val*bound)/max)*bound)%max;
rgb[2] = (((((val*bound)/max)*bound)/max)*bound)%max;
}
然而,我觉得对于这样一个简单的任务来说,这些方程中的很多似乎是不必要的。有没有更有效的方法来实现我忽略的这一点?
解决方案
看来您可能正在寻找类似以下的内容。如果没有,您需要澄清任务。
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
enum { NCounters = 3 }; // Number of elements in the counter array.
/* Add increment to the given counter. If it does not overflow, return 0.
If it overflows, reset the counter to 0 and report a carry.
*/
int AddOne(uint8_t increment, uint8_t counters[1])
{
unsigned a = counters[0] + increment;
if (256 <= a)
{
counters[0] = 0;
return 1;
}
else
{
counters[0] = a;
return 0;
}
}
/* Add increment to the counters, starting with the lowest counter and
proceeding to higher counters as long as there is a carry. If it does not
overflow out of all the counters, return 0. If it overflows, report a
carry.
*/
int Add(uint8_t increment, uint8_t counters[NCounters])
{
for (size_t i = 0; i < NCounters; ++i)
if (!AddOne(increment, &counters[i]))
return 0;
return 1;
}
int main(void)
{
// Initialize counters to zero.
uint8_t counters[NCounters] = { 0 };
/* Repeatedly print the counters and add the increment until the add
reports a carry out of the counters.
*/
do
{
printf("(%3d", counters[0]);
for (size_t i = 1; i < NCounters; ++i)
printf(", %3d", counters[i]);
printf(")\n");
} while (!Add(80, counters));
}
推荐阅读
- javascript - 将范围映射到单值 Javascript
- python - 使用正则表达式过滤字符串列表
- macos - mv 终端不允许操作
- firebase - 如何在 iOS XCUITest 期间配置 Firebase
- mysql - MySQL,选择不匹配的引用或引用在其他表中不存在
- hive - 为什么我不应该在 Impala 中的“COMPUTE STATS”和“COMPUTE INCREMENTAL STATS”之间切换?
- hadoop - 未找到压缩编解码器 com.hadoop.compression.lzo.LzoCodec
- python-3.x - 如何在python中更改特定类型变量的名称?
- javascript - Scrapy:从使用日期构造的 URL 中抓取 JSON 数据
- laravel - 在 Laravel 中将数据导出到 excel 调用未定义的错误