Can anyone please tell me how can I convert this float number: 12.25 to binary? I know how to convert the "12" but not the 0.25
Any help is much appreciated. Thanks
This question is related to
binary
floating-point
void transfer(double x) {
unsigned long long* p = (unsigned long long*)&x;
for (int i = sizeof(unsigned long long) * 8 - 1; i >= 0; i--) {cout<< ((*p) >>i & 1);}}
x = float(raw_input("enter number between 0 and 1: "))
p = 0
while ((2**p)*x) %1 != 0:
p += 1
# print p
num = int (x * (2 ** p))
# print num
result = ''
if num == 0:
result = '0'
while num > 0:
result = str(num%2) + result
num = num / 2
for i in range (p - len(result)):
result = '0' + result
result = result[0:-p] + '.' + result[-p:]
print result #this will print result for the decimal portion
The float value is stored in IEEE 754 format so we can't convert it directly like integer, char to binary.
But we can convert float to binary through a pointer.
#include <stdio.h>
int main()
{
float a = 7.5;
int i;
int * p;
p = &a;
for (i = sizeof(int) * 8 - 1; i >= 0; i--)
{
printf("%d", (*p) >> i & 1);
}
return 0;
}
Output
0 10000001 11100000000000000000000
Spaces added for clarification, they are not included as part of the program.
(d means decimal, b means binary)
Consider below example
We will consider the integer and fractional part separately.
The integral part is easy, 2 = 10.
For the fractional part:
0.625 × 2 = 1.25 1 Generate 1 and continue with the rest.
0.25 × 2 = 0.5 0 Generate 0 and continue.
0.5 × 2 = 1.0 1 Generate 1 and nothing remains.
So 0.625 = 0.101, and 2.625 = 10.101.
See this link for more information.
Source: Stackoverflow.com