简体   繁体   English

在 C 中仅使用 8 位算术将 8 位数字从 0-255 缩放到 0-100 的简单方法?

[英]Easy way in C to scale 8-bit number from 0-255 to 0-100 using only 8-bit arithmetic?

I have an 8-bit unsigned number from 0-255.我有一个 0-255 的 8 位无符号数。 I need to scale it to 0-100 without using anything other than 8-bit integer arithmetic, including casting, copying to other variables, etc. due to a micro controller limitation.由于微控制器的限制,我需要将它缩放到 0-100,而不使用 8 位整数算法以外的任何东西,包括强制转换、复制到其他变量等。

What is an accurate way for me to do this scaling?我进行这种缩放的准确方法是什么?

You will need to use 16 bits for this.为此,您将需要使用 16 位。

101 除以 256

Put the value in the high byte of a 16-bit register and:将值放在 16 位寄存器的高字节中,然后:

x >> 2 + x >> 3 + x >> 6 + x >> 8

The result will be in the high byte of the register.结果将在寄存器的高字节中。

Implementation using only 8-bit registers is left as an exercise for the reader.仅使用 8 位寄存器的实现留给读者作为练习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM