-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhex2float.c
More file actions
60 lines (54 loc) · 1.14 KB
/
hex2float.c
File metadata and controls
60 lines (54 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <stdio.h>
#include <stdint.h>
// float to hex
uint32_t float_to_hex(float val)
{
uint32_t num =0 ;
float fval = val;
num = *(uint32_t *)&fval;
printf("0x%x\n",num);
return num;
}
// 1. first method
float hex2float(uint8_t *val, int len)
{
uint32_t temp=0 ;
float fval;
temp = val[3] | temp;
temp = val[2] << 8 | temp;
temp = val[1] << 16 | temp;
temp = val[0] << 24 | temp;
fval = *(float *)&temp;
printf("%f\n",fval);
}
// 2. second method
float hex2Float(uint8_t *val)
{
uint32_t temp = 0;
float out = 0.0;
char tempS[32] = {0};
uint32_t num = 0;
temp = val[3] | temp;
temp = val[2] << 8 | temp;
temp = val[1] << 16 | temp;
temp = val[0] << 24 | temp;
sprintf(tempS, "%lx", temp);
sscanf(tempS, "%lx", &num);
out = *((float *)&num);
printf("%f\n",out);
return out;
}
uint8_t arr1[] = {0x42, 0xf7 ,0x00 ,0x00};
//42f70000 // 123.5
uint8_t arr2[] = {0x43, 0x47 ,0xfc ,0xac};
//0x4347fcac // 199.987
int main()
{
printf("Hello World\n");
hex2float(arr1,4);
hex2Float(arr1);
hex2float(arr2,4);
hex2Float(arr2);
float_to_hex(123.567);
return 0;
}