Convert decimal fraction to binary number - GeeksforGeeks
Given an fraction decimal number n and integer k, convert decimal number n into equivalent binary number up-to k precision after decimal point.
Auxiliary space: O(len(n))
http://www.geeksforgeeks.org/convert-binary-fraction-decimal/
Read full article from Convert decimal fraction to binary number - GeeksforGeeks
Given an fraction decimal number n and integer k, convert decimal number n into equivalent binary number up-to k precision after decimal point.
Input: n = 2.47, k = 5 Output: 10.01111Time complexity: O(len(n))
Auxiliary space: O(len(n))
string decimalToBinary(
double
num,
int
k_prec)
{
string binary =
""
;
// Fetch the integral part of decimal number
int
Integral = num;
// Fetch the fractional part decimal number
double
fractional = num - Integral;
// Conversion of integral part to
// binary equivalent
while
(Integral)
{
int
rem = Integral % 2;
// Append 0 in binary
binary.push_back(rem +
'0'
);
Integral /= 2;
}
// Reverse string to get original binary
// equivalent
reverse(binary.begin(),binary.end());
// Append point before conversion of
// fractional part
binary.push_back(
'.'
);
// Conversion of fractional part to
// binary equivalent
while
(k_prec--)
{
// Find next bit in fraction
fractional *= 2;
int
fract_bit = fractional;
if
(fract_bit == 1)
{
fractional -= fract_bit;
binary.push_back(1 +
'0'
);
}
else
binary.push_back(0 +
'0'
);
}
return
binary;
}
http://www.geeksforgeeks.org/convert-binary-fraction-decimal/
Given an string of binary number n. Convert binary fractional n into it’s decimal equivalent.
Input: n = 110.101 Output: 6.625
double
binaryToDecimal(string binary,
int
len)
{
// Fetch the radix point
size_t
point = binary.find(
'.'
);
// Update point if not found
if
(point == string::npos)
point = len;
double
intDecimal = 0, fracDecimal = 0, twos = 1;
// Convert integral part of binary to decimal
// equivalent
for
(
int
i = point-1; i>=0; --i)
{
// Subtract '0' to convert character
// into integer
intDecimal += (binary[i] -
'0'
) * twos;
twos *= 2;
}
// Convert fractional part of binary to
// decimal equivalent
twos = 2;
for
(
int
i = point+1; i < len; ++i)
{
fracDecimal += (binary[i] -
'0'
) / twos;
twos *= 2.0;
}
// Add both integral and fractional part
return
intDecimal + fracDecimal;
}
Read full article from Convert decimal fraction to binary number - GeeksforGeeks