The function returns the value of the
loc
bit of the integer variable
num
. Note you could rewrite it this way
int float_bit_return(int num, int loc)
{
return ((num >> loc) & 1);
}
(the inner braces are not needed due to
C
operator precedence rules, but I find the code more readable with them).
You may actually use use such a function to inspect the bits of a float value, as the following code shows (it assumes
sizeof(float)==sizeof(int)
)
#include <stdio.h>
int float_bit_return(int num, int loc)
{
return ((num >> loc) & 1);
}
int main()
{
int i = 5;
float f = 3.25f;
printf("bits of the integer value %d\n", i);
for (int n=0; n<sizeof(int)*8; ++n)
printf("%02d %d\n", n, float_bit_return(i, n));
printf("bits of the float value %f\n", f);
for (int n=0; n<sizeof(int)*8; ++n)
printf("%02d %d\n", n, float_bit_return(*(int*)&f, n));
return 0;
}
Output:
[...]
bits of the float value 3.250000
00 0
01 0
02 0
03 0
04 0
05 0
06 0
07 0
08 0
09 0
10 0
11 0
12 0
13 0
14 0
15 0
16 0
17 0
18 0
19 0
20 1
21 0
22 1
23 0
24 0
25 0
26 0
27 0
28 0
29 0
30 1
31 0
with
sign: bit
31
equal to zero ->
positive number
exponent bits
30-23 = 128 -> 2^1
mantissa bits
22-0 = .101b -> 1.101b
so,
f = 1.101b * 2^1 = 11.01b = 3.25
[update]
The same result could be obtained using a (possibly more intuite)
union
:
#include <stdio.h>
int float_bit_return(int num, int loc)
{
return ((num >> loc) & 1);
}
int main()
{
union {
int i;
float f;
} u;
u.f = 3.25;
printf("bits of the float value %f\n", u.f);
for (int n=0; n<sizeof(int)*8; ++n)
printf("%02d %d\n", n, float_bit_return( u.i, n ));
return 0;
}
[/update]