Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- #define sz(x) int(x.size())
- #define nl "\n"
- void binToOctal(){
- string num ;
- cout << "Enter the number in binary to convert it to octal : ";
- cin >> num;
- map < string , int > mp; // store the first 3 digit to equal it in decimal
- mp["000"]=0 , mp["001"]=1 , mp["010"]=2 , mp["011"]=3,
- mp["100"]=4 , mp["101"] =5 , mp["110"]= 6, mp["111"] =7;
- int idx =-1;
- for(int i = 0; i < num.size() ; i++){
- if(num[i]=='.'){
- idx = i;
- break;
- }
- }
- string temp; // contain the part before floating point
- if(idx ==-1) // no floating point
- temp = num ;
- else
- temp = num.substr(0 , idx);
- string ans="";
- int mod = int(temp.size()) % 3;
- if(mod){
- mod = 3- mod;
- while(mod--) ans+='0';
- }
- ans+= temp;
- string result ="";
- for(int i=0 ; i < ans.size() ; i+=3){
- string st = ans.substr(i , 3);
- result+= '0'+ mp[st];
- }
- if(idx!=-1){ // contain floating point
- result+='.';
- string point= num.substr(idx+1);
- int mod2= int (point.size())% 3 ;
- if(mod2){
- mod2= 3- mod2 ;
- while(mod2--) point +='0';
- }
- for(int i=0 ; i < point.size() ; i+=3){
- string st2 = point.substr(i , 3);
- result+= '0'+ mp[st2];
- }
- }
- cout <<"octal number : " << result << nl;
- }
- int main() {
- binToOctal();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement