Bitmasking with floats and doubles

Started by
7 comments, last by Mr Cucumber 20 years, 9 months ago
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?
Advertisement
float myfloat = whatever;unsigned int myuint = reinterpret_cast<unsigned int&>(myfloat);
...then use bit operations to get the chars from the unsigned int.
Is the point of reinterpret_cast to maintain the bits in the float the exact same way in the int?
why not
char * bytes = (char *)&aFloat 

now the four bytes are in bytes[0 through 3].
quote: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.
Im trying to step away from the C ways of doing things. I realised recently that I do a lot of things in deprecated ways. Thanks all anyway.
When you cast it to int you use a reference int, why is that necessary?

[edited by - Mr Cucumber on July 26, 2003 8:26:47 AM]
if & isn''t between a type and a name, it is used to get the adress of the variable right to it...
[s]--------------------------------------------------------[/s]chromecode.com - software with source code
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

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

floatchar.f=1.3242;

printf(floatchar.c[0]);
printf(floatchar.c[1]);
...

you get the idea , enjoy

This topic is closed to new replies.

Advertisement