將 modbus RTU 過(guò)來(lái)的十六進(jìn)制的資訊(如:41 E1 32 F2) 轉(zhuǎn)換成小數(shù)(28.149876)(IEEE 754)
復(fù)制代碼- #include <stdio.h> // printf
- #include <stdlib.h> // system("pause")
- #include <stdint.h> // uint8_t
- #include <string.h> // memcpy
- float raw2ieee(uint8_t *raw)
- {
- // either
- union {
- uint8_t bytes[4];
- float fp;
- } un;
- memcpy(un.bytes, raw, 4);
- return un.fp;
- // or, as seen in the fast inverse square root:
- return *(float *)raw;
- }
- int main(int argc, char *argv[])
- {
- uint8_t val[64]; //declare input value recieved from serial connection
-
- int i=0;
-
- // your 0xXX here
- val[i]=0xf2; // Low
- val[i+1]=0x32; //
- val[i+2]=0xe1; //
- val[i+3]=0x41; // High
-
- printf("Raw: %X %X %X %X\n",val[i+3],val[i+2],val[i+1],val[i]);
- printf("Float: %f \n\n", raw2ieee(val)); //show the value in float
-
- system("pause");
- //getchar( ); // stdio.h
- }
- /* RESULT */
- // Raw1: 41 E1 32 F2
- // Float: 28.149 876
- //
- // 請(qǐng)按任意鍵繼續(xù) . . .
|