Building a 32-bit float out of its 4 composite bytes

前端 未结 6 942
渐次进展
渐次进展 2020-11-27 05:10

I\'m trying to build a 32-bit float out of its 4 composite bytes. Is there a better (or more portable) way to do this than with the following method?

#includ         


        
6条回答
  •  失恋的感觉
    2020-11-27 06:00

    The following functions pack/unpack bytes representing a single precision floating point value to/from a buffer in network byte order. Only the pack method needs to take endianness into account since the unpack method explicitly constructs the 32-bit value from the individual bytes by bit shifting them the appropriate amount and then OR-ing them together. These functions are only valid for C/C++ implementations that store a float in 32-bits. This is true for IEEE 754-1985 floating point implementations.

    // unpack method for retrieving data in network byte,
    //   big endian, order (MSB first)
    // increments index i by the number of bytes unpacked
    // usage:
    //   int i = 0;
    //   float x = unpackFloat(&buffer[i], &i);
    //   float y = unpackFloat(&buffer[i], &i);
    //   float z = unpackFloat(&buffer[i], &i);
    float unpackFloat(const void *buf, int *i) {
        const unsigned char *b = (const unsigned char *)buf;
        uint32_t temp = 0;
        *i += 4;
        temp = ((b[0] << 24) |
                (b[1] << 16) |
                (b[2] <<  8) |
                 b[3]);
        return *((float *) &temp);
    }
    
    // pack method for storing data in network,
    //   big endian, byte order (MSB first)
    // returns number of bytes packed
    // usage:
    //   float x, y, z;
    //   int i = 0;
    //   i += packFloat(&buffer[i], x);
    //   i += packFloat(&buffer[i], y);
    //   i += packFloat(&buffer[i], z);
    int packFloat(void *buf, float x) {
        unsigned char *b = (unsigned char *)buf;
        unsigned char *p = (unsigned char *) &x;
    #if defined (_M_IX86) || (defined (CPU_FAMILY) && (CPU_FAMILY == I80X86))
        b[0] = p[3];
        b[1] = p[2];
        b[2] = p[1];
        b[3] = p[0];
    #else
        b[0] = p[0];
        b[1] = p[1];
        b[2] = p[2];
        b[3] = p[3];
    #endif
        return 4;
    }
    

提交回复
热议问题