# 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; } ```  結果是3,我們想要的並非這樣的結果,而是不捨棄float中的小數部分。  #### 方法一: 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; } ```  #### 方法二: 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; } ``` 
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up