[英]Expression Evaluation in 32 bit CPU
I am working with TIs 32 bit microcontroller TMS320F280049.我正在使用 TI 32 位微控制器 TMS320F280049。 I am using an external ADC for temperature measurement.
我正在使用外部 ADC 进行温度测量。 The ADC output code is of 24 bit data, now I want convert this ADC output code to resistance value by using the following expression
ADC output 代码是 24 位数据,现在我想使用以下表达式将此 ADC output 代码转换为电阻值
RTD = (1080 * ADC output code) / (4194304 * 16)
and I wrote the code as follows,我写的代码如下,
int32 RTD = 0;
int32 adc = 0x005EEC17;
RTD = (1080*adc)/(16*4194304);
I wrote this expression as it is but got RTD value some random negative value instead of 100 which I am expecting.我按原样写了这个表达式,但得到的 RTD 值是一些随机的负值,而不是我期望的 100。 I wonder how to correctly evaluate the expression.
我想知道如何正确评估表达式。 I am beginner in coding any explanation that put into simple words will be greatly appreciated.
我是编码任何解释的初学者,将不胜感激。
1080*0x005EEC17
overflows int32
. 1080*0x005EEC17
溢出int32
。 Therefore you need to do the math in a wider type.因此,您需要以更广泛的类型进行数学运算。 You can use the
LL
suffix to make the literal long long
which is at least 64-bit您可以使用
LL
后缀使文字long long
至少为 64 位
int32 RTD = 0;
int32 adc = 0x005EEC17;
RTD = (1080LL*adc)/(16*4194304);
An int32_t
can only store values up to 2 31 –1 (approximately 2.15e9). int32_t
最多只能存储 2 31 –1(大约 2.15e9)的值。 Multiplying 1080 * adc
(approx. 6.7e9) will result an overflow.乘以
1080 * adc
(约 6.7e9)将导致溢出。 Here are some alternatives that seem to work with gcc:以下是一些似乎适用于 gcc 的替代方案:
uint32_t rtd = adc / 16 * 1080 / 4194304; // Dividing first.
uint32_t rtd = (adc >> 4) * 1080 / 4194304; // Same as above.
uint32_t rtd = (adc * 1080.0) / (16 * 4194304); // Implicitly convert to double, so that larger values can be stored.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.