How to convert float to byte array of length 4 (array of char*)?

前端 未结 3 1546
傲寒
傲寒 2021-02-15 17:23

How to convert float to byte array of length 4 (array of char*) ? I need to send over network some data, tcp, and need to send float as a byte array. ( I know precision to two d

3条回答
  •  梦如初夏
    2021-02-15 18:18

    Reading any type as a sequence of bytes is quite simple:

    float f = 0.5f;
    
    unsigned char const * p = reinterpret_cast(&f);
    
    for (std::size_t i = 0; i != sizeof(float); ++i)
    {
        std::printf("The byte #%zu is 0x%02X\n", i, p[i]);
    }
    

    Writing to a float from a network stream works similarly, only you'd leave out the const.

    It is always permitted to reinterpret any object as a sequence of bytes (any char-type is permissible), and this expressly not an aliasing violation. Note that the binary representation of any type is of course platform dependent, so you should only use this for serialization if the recipient has the same platform.

提交回复
热议问题