This topic is now archived and is closed to further replies.

Mr Cucumber

Bitmasking with floats and doubles

Recommended Posts

What I want to do is to take a float and bitmask out each of the for bytes in the float and save each byte in a char. This is how I tried to do it:
float bytes = whatever;
      //Filter out the bytes with a binary mask

	char byteLowest = static_cast<char> (bytes & 255);
	char byteSecondLowest = static_cast<char> ((bytes & 65280) >> 8);
	char byteSecondHighest = static_cast<char> ((bytes & 16711680) >> 16);
	char byteHighest = static_cast<char> ((bytes & 4278190080) >> 24);
Apparently the compiler dont like binary operations on floats. What can I do to perform what I want?

Share this post

Link to post
Share on other sites
Original post by Mr Cucumber
Is the point of reinterpret_cast to maintain the bits in the float the exact same way in the int?
Yeah; it''s one way to reinterpret the underlying bits. Such reinterpretation can also be done with a union, or with a C-style cast, as billybob pointed out.

Share this post

Link to post
Share on other sites
to take the bits out of a float/double , you cant cast it to something else , because cast tries to change the varible to the new type , like if you cast a float like 12.42 to an int , you will get 12 !.

they showed you how to do it and i will explain :
take the float "f" , now the its address "&f" , now you have pointer to the place where the float is in memory , now you tell the compiler that the pointer is not pointing to a float but to and int (the same number of bits) "(*int)&if" .
ok now we want the actuall bits and not a pointer so we tell the compiler we want whats in that address

"int i=*((int*)&f)" , this is little ugly so you can do this in nicer way like this

float f;
char c[4];
} floatchar;



you get the idea , enjoy

Share this post

Link to post
Share on other sites