Getting the IEEE Single-precision bits for a float

后端 未结 4 1731
长情又很酷
长情又很酷 2021-01-07 03:54

I need to write an IEEE single-precision floating point number to a 32-bit hardware register at a particular address. To do that, I need to convert a variable of type float

4条回答
  •  走了就别回头了
    2021-01-07 03:59

    EDIT: The union solution works everywhere I have tried it but somewhere on SO I had been pointed at standards that showed it didnt have to work. See the link below in the comments to find a LOT more info on this (Thank you Daniel!). Supposed to work or not supposed to work I would use it with care, I imagine endianness, etc gets involved as well (doubles broken into bytes, etc).

    Another solution is a dummy asm function. For example on arm:

    .globl echo 
    echo:
       bx lr
    
    
    unsigned int echo ( float );
    ...
    unsigned int ra; float f;
    f=1.0;
    ra=echo(f);
    

    some disassembly is required, needs to be on a system that doesnt have an fpu and/or uses gprs for carrying around floats.

    memcpy as already mentioned is the cleanest and most reliable and portable solution (be aware of endianness).

提交回复
热议问题