문제

I have this simple union:

union {
    char c[4];
    float f;
} u;
u.c[3] = 0x42;
u.c[2] = 0xc9;
u.c[1] = 0x00;
u.c[0] = 0x00;

cout << u.f << endl;

I got a file filled with hexa values like this one. I need to convert them to ieee 754 float and this union does it just fine. The problem is I also need the binary version of these numbers. The question is what is the shorter/more efficient way to do this: read this union like binary or convert the hexa value to binary?

Can I read it as binary? Or should I just convert the hexa value (0x0000c942) to binary?

도움이 되었습니까?

해결책

Actually you can print anything as binary easily. Below examples on how to print 32 bit binary:

void bin32_print(void *bit32_stuff)
{
    int val = *((int*)bit32_stuff);

    for(int cnt = 32; cnt; cnt--, val <<= 1)
    {
        cout << ((val&0x80000000)?'1':'0');
    }

    cout << endl;
}

// 0xFFAA0102 is 11111111101010100000000100000010
int int32_val = 0xFFAA0102;
bin32_print(&int32_val);

// 1.234f = 0x3F9DF3B6 = 00111111100111011111001110110110    
float float32_val = 1.234f;
bin32_print(&float32_val);

다른 팁

In C, there is no way (i.e. a language feature) to read as binary, so the only way to achive this is to implement your own conversion method. Using the hex value, as you asked, is an appropiate method.

But, if you want to do this to see the binary representation, this is the wrong way. In general, when working with binary representation, people work actually with hexadecimal representation. That is because every hexadecimal digit represent 4 known bits from the binary representation. With some practice, you can 'see' the binary representation in hexadecimal. This is preffered, as it is a shorter representation.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top