C++ - convert floating point number to 4 bytes

In C++, you can use bit operations and shift operations to convert floating point numbers to 4 bytes.
Here is a sample code:

#include <iostream>  
#include <bitset>  
  
int main() {  
    float num = 3.14159f;  
    unsigned char bytes[4];  
  
    // 将浮点数转换为32位无符号整数  
    uint32_t uint_num = *(reinterpret_cast<uint32_t*>(&num));  
  
    // 将无符号整数转换为4个字节的数组  
    for (int i = 0; i < 4; i++) {  
        bytes[i] = uint_num & 0xFF;  
        uint_num >>= 8;  
    }  
  
    // 打印每个字节的值  
    for (int i = 0; i < 4; i++) {  
        std::cout << std::bitset<8>(bytes[i]) << " ";  
    }  
    std::cout << std::endl;  
  
    return 0;  
}

In the above code, the address of the floating-point number num is first cast to a pointer of type uint32_t* and then dereferenced to obtain the unsigned integer representation of num. Next, convert the unsigned integer to an array of 4 bytes using bitwise and shift operations. Finally, the value of each byte is printed.

Note that during the conversion, we used reinterpret_cast to convert the pointer of type float to a pointer of type uint32_t*. This is an unsafe operation because it may result in undefined behavior. Therefore, great care should be taken when using reinterpret_cast to ensure that no problems arise.

4 bytes to float

Guess you like

Origin blog.csdn.net/weixin_44697721/article/details/131722790