Bitwise << and floats

Hi!

Trying to read all the bits in a float and write them to a string by doing something like:

for( unsigned int Iterator = 0; Iterator < 32; Iterator++ ) {

if( ( unsigned int )FromFloat & ( unsigned int )0x80000000 )
ToString[ Iterator ] = '1'
;
else ToString[ Iterator ] = '0'
;

( unsigned int )FromFloat <<= 1;

}

The actual problem is this: error C2106: '<<=' : left operand must be l-value. Now I can't even begin to see why the compiler doesn't think it can write to "( unsigned int )FromFloat". And skipping the type casting is even worse as it seems bitwise operations are illegal on floats.

TIA!

, Espen



Answer this question

Bitwise << and floats

  • Giorgio Sardo

    Why not using a bitset

     

     float f = 14.45;
     float f = 14.45;
     const int bitsno = 8 * sizeof(float);
     unsigned int* pf = (unsigned int*)&f;
     std::bitset<bitsno> fbits(*pf);
    
     string s = fbits.to_string<char, char_traits<char>, allocator<char> >();
    
     std::cout << s << std::endl;
    

     



  • leonreet

    In my opinion you should consider the following approach too:

    assert(sizeof(float) == sizeof(int));

     

    float f = 14.45f;

    char s[sizeof(float) * 8 + 1];

    int k = (int&)f;

     

    int i;

    for( i = 0; i < sizeof(float) * 8; ++i)

    {

           s[ i ] = k < 0 '1' : '0';

           k <<= 1;

    }

    s[ i ] = 0;

     

    // or instead of for loop: _itoa_s(k, s, sizeof(s), 2);< xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

     

    std::cout << s << std::endl;

    // displays "01000001011001110011001100110011";

    I hope after adjustments it will be suitable for you. Your original attempt actually seems to work with truncated values.


  • DanInNewWest

    Thanx for your help. Modifying a very small part of my code after reading your example worked perfectly:

    float Float = 1346.98f;
    unsigned int _Float = ( unsigned int & )Float;

    And then using _Float throughout the code worked.

    , Espen


  • Bitwise << and floats