---
# System prepended metadata

title: C Type Casting
tags: [C basics]

---

# C Type Casting
###### tags: `C basics`
#### 整理：BY.Y, 2022/02/10
#### src: 
1. https://stackoverflow.com/questions/41661029/store-float-value-in-uint32-t-pointer
2. IEEE-754 online converter: https://www.h-schmidt.net/FloatConverter/IEEE754.html


### 前情提要
<p>在Nordic RF傳輸，規定的傳輸型態是uint32_t，而我們原始資料是float，想要將float裝到一個uint32_t該怎麼做?</p>

```c=
#include <stdio.h>
#include <stdint.h>
int main(void)
{
    float pi = 3.14159;
    uint32_t tmp = (uint32_t)pi;
    
    printf("after type cast: %x\n", tmp);
    return 0;
}
```
![](https://i.imgur.com/Z9Mqznu.png)
結果是3，我們想要的並非這樣的結果，而是不捨棄float中的小數部分。
![](https://i.imgur.com/awO1ihr.png)

#### 方法一: memcpy
根據reference 1:
```c=
#include <stdio.h>
#include <stdint.h>
#include <string.h>
int main()
{
    float pi = 3.14159;
    uint32_t tmp = 0;
    memcpy(&tmp, &pi, sizeof(float));
    printf("after type cast: 0x%x\n", tmp);

    return 0;
}
```
![](https://i.imgur.com/Vq3EvLX.png)

#### 方法二: union
同樣根據reference 1:
```c=
#include <stdio.h>
#include <stdint.h>
#include <string.h>
int main()
{
    float pi = 3.14159;
    uint32_t tmp = 0;
    memcpy(&tmp, &pi, sizeof(float));
    printf("after type cast: 0x%x\n", tmp);

    return 0;
}
```
![](https://i.imgur.com/Ja0zf60.png)
