Converting 'float' to 'byte[4]' and back to 'float' in .NET Micro Framework

后端 未结 3 1695
清歌不尽
清歌不尽 2020-12-06 13:17

What\'s the best way to convert a float to a byte[4] and then back to a \'float\'?

I am doing this in C# .NET Micro Framework, so there is

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-06 14:08

    This worked for me, may not be the most complete answer but simple

    void floatToByte(GLubyte b[], float n)
    {
    unsigned int val = *((unsigned int*)&n);
    
    b[0] = (GLubyte)(val  & 0xFF);
    b[1] = (GLubyte)((val >> 8) & 0xFF);
    b[2] = (GLubyte)((val >> 16) & 0xFF);
    b[3] = (GLubyte)((val >> 24) & 0xFF);   
    }
    
    
    
    float byteToFloat(GLubyte b[])
    {
    unsigned int ret =  (unsigned int)(b[0] << 0 | b[1] << 8 | b[2] << 16 | b[3] << 24);
    float r = *(((float*)&ret));
    return r;
    }
    

提交回复
热议问题