extract bits from 32 bit float numbers in C

筅森魡賤 提交于 2021-02-08 10:36:30

问题


32 bits are represented in binary using the IEEE format. So how can I extract those bits? Bitwise operations like & and | do not work on them! what i basically want to do is extract the LSB from 32 bit float images in opencv thanx in advance!


回答1:


uint32_t get_float_bits(float f) {
    assert(sizeof(float) == sizeof(uint32_t)); // or static assert
    uint32_t bits;
    memcpy(&bits, &f, sizeof f);
    return bits;
}

As of C99, the standard guarantees that the union trick works (provided the sizes match), and implementations have generally guaranteed it even before they were required to. Personally I don't know what people see in it, I prefer this.

If you just want the LSB, and you know the endian-ness, you can access just one byte of the float directly, without any memcpy, or union, or violation of strict aliasing.

int lsb = ((unsigned char*)&f)[0] & 1; // little-endian
int lsb = ((unsigned char*)&f)[sizeof(float)-1] & 1; // big-endian



回答2:


You can use a union to pull values out safely (demo):

union fi_t
{
    unsigned int i;
    float f;
};

fi_t fi;
fi.f = 1.5;
unsigned int i = fi.i;

(just never typecast, this will invoke dreaded ftol, which may use SSE2 to convert to integer form, or FISTP, which won't yield the IEEE bits you are after)




回答3:


The old trick:

float num = 0.5;
uint32_t binary_representation = *(uint32_t *)#



回答4:


#include<stdio.h>
union abc
{
    float fo;
    unsigned int no;
};
int main()
{   
    union abc test;
    test.fo=36.5;
    unsigned int x=test.no;
    for( int i = 0; i < sizeof(float)*8; i++ )
    {
        printf("%d", x & 0x1);
        x = x >> 1;
    }

    return 0;
}

this was a way to extract the bits of the float!



来源:https://stackoverflow.com/questions/11136408/extract-bits-from-32-bit-float-numbers-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!