• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Interesting C++ interview question

Page 2 - Seeking answers? Join the AnandTech community: where nearly half-a-million members share solutions and discuss the latest tech.
I'm not a C++ developer but would something like this work?

Copied From...

Shifting Bits for other types
Suppose you wish to shift left on float variables. The compiler will complain that you can't do this. Bitwise/bitshift operations aren't defined on float variables. So, what can you do?

Trick the compiler.

How do you do that?

Make it think the float is an int.

Here's the wrong way to do it. You can try to cast the float to an int. But if you do this, you have two problems. First, casting creates a temporary value. Even if you save this, the bits will actually change. A float that's cast to an int causes the fractional part to be truncated, and what's more, it changes the representation from IEEE 754 to 2C.

Nevertheless, casting is the right idea. Here's how to do it.

float x ;
int * ptr = (int *) (& x) ;
*ptr <<= n ; // left shift by n bits

You make a pointer that points to the float with same number of bytes, then you shift based on the dereferenced pointer. At this point, when we manipulate *ptr, we're actually manipulating x.
 
Back
Top