My goal here is to display the binary representation of a float in the console. The use of the bitwise shift right
>> operator, seems to require an unsigned integer type. For this reason I am trying to convert a float to unsigned int.
Here is my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
#include <iostream>
#include <string>
std::string toBinary(const int &number)
{
unsigned int bitPattern(0x80000000); // MSB is 1, followed by 0's.
std::string binaryString("");
for (unsigned int bit(0); bit < 32; ++ bit) {
if ((bitPattern & number) > 0)
binaryString += "1";
else
binaryString += "0";
bitPattern >>= 1;
}
return binaryString;
}
int main()
{
std::cout << sizeof(float) << std::endl; // 4
std::cout << sizeof(unsigned int) << std::endl; // 4
float f = 3.14159f;
unsigned int f_ui = reinterpret_cast<unsigned int>(f); // ERROR!
std::cout << toBinary(f_ui) << std::endl;
return 0;
}
|
The compiler is giving me an error at line 23:
invalid cast from type 'float' to type 'unsigned int'
I chose unsigned int because it is represented by the same amount of bits as a float in my system. 4 bytes (32 bits).
I found another thread on this site;
http://www.cplusplus.com/forum/general/60160/ , with a very similar question. There is also a working solution to the problem given as a reply. That's great, but I would like to know more.
Why can't I
reinterpret_cast a type to another when they have the same size? Logically it seems like the least dangerous
reinterpret_cast operation I can think of.
All the examples I have seen of
reinterpret_cast deals with pointers.
Can reinterpret_cast ONLY be used with pointers? That is my main question.