I've managed to convert an array of char into a string but now I want to do the other way around, I tried using strcpy in my code but it doesn't seem to give me what I want. The expected result should be 5, I'm getting 40959 as a result
#include <iostream>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <algorithm>
using namespace std;
string DecToBin(int);
int BinToDec(string);
int main()
{
int x = 5;
string y = DecToBin(x);
reverse(y.begin(), y.end());
int z = BinToDec(y);
cout << z << endl;
}
string DecToBin(int num)
{
char res[16];
for (int n = 15; n >= 0; n--)
{
if ((num - pow(2, n)) >= 0)
{
res[n] = '1';
num -= pow(2, n);
}
else
{
res[n] = '0';
}
}
for (int n = 15; n >= 0; n--)
{
res[n];
}
return res;
}
int BinToDec(string num)
{
char x[16];
strcpy(x, num.c_str());
int res;
for (int n = 15; n >= 0; n--)
{
if (x[n] == '1')
{
res += pow(2, n);
}
}
return res;
}