0 points

binary to octal


dashboard

Sun Nov 15 2020 04:08:15 GMT+0000 (UTC)

Posted by @mahmoud hussein #c++

#include <iostream>
#include<cmath>
#include<ctime>
#include<string>
#include <iomanip>
#include <fstream>

using namespace std;

int octal2Dec(string& octal);
bool validity(int number);
int stringToNum(string number);
int bin2Dec(int binNumber);
int dec2octal(const string& number);




int main()
{
	string binNumber;
	getline(cin, binNumber);
	cout << dec2octal(binNumber);
	return 0;
}
int dec2octal(const string& number)
{
	int binNumber = stringToNum(number);
	int decimalNumber = bin2Dec(binNumber);
	int octal = 0, placeValue = 1;
	while (decimalNumber != 0)
	{
		octal += (decimalNumber % 8) * placeValue;
		decimalNumber /= 8;
		placeValue *= 10;
	}
	return octal;
}

int bin2Dec(int binNumber)
{
	int digits, decimal = 0, count = 0, bin = binNumber;
	while (bin != 0)
	{
		digits = bin % 10;
		  decimal += digits* pow(2,count);

		  bin /= 10;
		count++;
		
	}
	return decimal;
}
int stringToNum(string binNumber)
{
	int convertedNumber = 0;
	for (int i = 0; i < binNumber.length(); i++)
	{
		
		convertedNumber = (convertedNumber * 10) + static_cast<int>(binNumber[i] - '0');
	}
	return convertedNumber;
}
content_copy Copy

http://cpp.sh/