Multiplying a single point float with 2
This is a homework question. I've already found a lot of code on the internet, including some code on StackOverflow. But I just want the concept to be not code. I want to implement it myself. Thus, the function I want to implement is:
-
float_twice
- Returns the equivalent of the bit level expression for the2*f
floating point argumentf
. - Both arguments and result are passed as
unsigned int
, but must be interpreted as representing the single-precision floating point bit level.
I want to know how to do this. I know floating point representation. And read the wiki page on how to multiply two floats but didn't get it. I just want to know the concept / algorithm for it.
Edit:
Thanks everyone. Based on your suggestions, I wrote the following code:
unsigned float_twice(unsigned uf) {
int s = (uf >> 31) << 31;
int e = ((uf >> 23) & 0xFF) << 23;
int f = uf & 0x7FFF;
// if exponent is all 1 then its a special value NaN/infinity
if (e == 0xFF000000){
return uf;
} else if (e > 0){ //if exponent is bigger than zero(not all zeros', not al 1's,
// then its in normal form, add a number to the exponent
return uf + (1 << 23);
} else { // if not exponent not all 1 and not bigger than zero, then its all
// 0's, meaning denormalized form, and we have to add one to fraction
return uf +1;
} //end of if
} //end of function
source to share
You can do something like this (although some would argue that it violates anti-aliasing rules):
unsigned int func(unsigned int n)
{
float x = *(float*)&n;
x *= 2;
return *(unsigned int*)&x;
}
void test(float x)
{
unsigned int n = *(unsigned int*)&x;
printf("%08X\n",func(n));
}
In any case, you will need to assert that the size float
is equal to the size int
on your platform.
If you just want to take an operand unsigned int
and perform the equivalent operation of multiplying a float
by 2 on it, then you can simply add 1 to its exponential part (located in bits 20-30)
unsigned int func(unsigned int n)
{
return n+(1<<20);
}
source to share