I've got two integer numbers in binary form, num1
and num2
stored as strings containing "0"s and "1"s.
What would be the best algorithm to divide num1
by num2
in order to obtain a floating-point double
result?
I've got two integer numbers in binary form, num1
and num2
stored as strings containing "0"s and "1"s.
What would be the best algorithm to divide num1
by num2
in order to obtain a floating-point double
result?
Assuming your strings are in big-endian binary format, which is the most natural way to represent a binary number as a string, here is how you could convert each str
to a double val
:
double val = 0.0;
while (0 != *str) {
val *= 2.0;
if ('1' == *str) val += 1.0;
str++;
}
Then divide the doubles.
#include<iostream>
#include<cmath>
int stringToNum(std::string str){
int num=0;
for(size_t i=0;i<str.size();i++){
if(str[i]=='1'){num+=pow(2,str.size()-i-1);}
}
return num;
}
int main(){
std::string str1,str2;
std::cin>>str1>>str2;
int num1 = stringToNum(str1);
int num2 = stringToNum(str2);
std::cout << (float)num1/num2 << '\n';
}
Code could follow primary school math.
Align the dividend and divisor.
Loop DOUBLE_BITS times
Test divisor and dividend
If big enough, subtract and add to quotient
Shift
Below is untested code, so treat as pseudo-code to OP an idea of a solution.
double str_div(const char * num1, const char *num2) {
while (*num1 == '0') num1++; // find ms bit
while (*num2 == '0') num2++;
if (*num2 == '\0') {
if (*num1) return 1.0/0.0;
return 0.0/0.0;
}
size_t sz1 = strlen(num1) + 1;
size_t sz2 = strlen(num2) + 1;
double m = pow(2, 1.0* sz1 - sz2);
#define DOUBLE_BITS 53
size_t szmx = max(sz1, sz2);
size_t sza = szmx + DOUBLE_BITS + 1;
// form working register `a`
char *a = malloc(sza);
memset(a, '0', sza);
memcpy(a, num1, sz1 - 1);
a[sz1 - 1] = '\0';
double quotient = 0.0;
for (size_t i=0; i<DOUBLE_BITS; i++) {
if (str_ge(a, num2)) { // a >= num2?
str_sub(a, num2); // a -= num2
quotient += m;
}
m /= 2.0;
}
free(a);
return quotient;
}