簡體   English   中英

浮點數到換算的int轉換

[英]floating point to scaled int conversion

我下面有一個使用浮點數D1D2的函數。 它們是方程式中的變量。

我不想使用浮點數,我在開發的嵌入式平台上受限於內存(浮點庫很大)。 我只想使用int 因此,該函數將返回int並在計算中使用int

例如,該函數將返回229500度,而不是22.95度。

有人知道我如何計算D1D2應該變成什么值嗎?

該函數返回的值的取值范圍是-40至120度。

一個int的大小為4個字節。

float readTemperatureC()
{
  int val;                // Raw value returned from sensor
  float temperature;      // Temperature derived from raw value

  // Conversion coefficients from SHT15 datasheet
  const float D1 = -40.0;  // for 14 Bit @ 5V
  const float D2 =   0.01; // for 14 Bit DEGC

  // Fetch raw value
  val = readTemperatureRaw();

  // Convert raw value to degrees Celsius
  temperature = (_val * D2) + D1;

  return (temperature);
}

這是我要轉換為僅使用整數的函數。 int readTemperatureC(){int val; //從傳感器int溫度返回的原始值; //從原始值得出的溫度

  // Conversion coefficients from SHT15 datasheet
  const int D1 = ?;  // for 14 Bit @ 5V
  const int D2 = ?; // for 14 Bit DEGC

  // Fetch raw value
  val = readTemperatureRaw();

  // Convert raw value to degrees Celsius
  temperature = (val * D2) + D1;

  return (temperature);
}

而不是22.95度,該函數將返回229500度。

將系數乘以10,000,然后使用整數算術。

// Conversion coefficients from SHT15 datasheet
// const float D1 = -40.0;  // for 14 Bit @ 5V
// const float D2 =   0.01; // for 14 Bit DEGC
const int D1 = (int) (-40.0*10000);
const int D2 = (int) (0.01*10000);
...
temperature = (_val * D2) + D1;

注意:OP聲明4字節int


查看 數據表后,我懷疑FP值 -40.00.01是否正確

OP已評論了正確的數據表 從第4.3節溫度開始

表8
d 1 (VDD = 5伏)= -40.1°C
d 2 = 0.01°C

T = d 1 + d 2 * SO T

#define d1 (-40.1 /* degrees C */)
#define d2 (0.01 /* degrees C/d2a */)

#define T_SCALE 10000
#define T_OFFSET ((int)(d1 * SCALE))
#define T_SLOPE  ((int)(d2 * SCALE))

// Sensor output - temperature
// 0 to 0x3FFF (14-bit)
int SOT = readTemperatureRaw();

// temeprature in 1/10,000 degree C
int temperature = (SOT * T_SLOPE) + T_OFFSET;

// With 32-bit `int`, no range issue
// -401000 <= temperature <= 1237300

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM