Advertisement
Zeinab_Hamdy

binary2octal

Apr 7th, 2023 (edited)
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. #define sz(x) int(x.size())
  4. #define nl "\n"
  5.  
  6.  
  7. void binToOctal(){
  8.  
  9.     string num ;
  10.     cout << "Enter the number in binary to convert it to octal : ";
  11.     cin >> num;
  12.  
  13.  
  14.     map < string , int > mp;    // store the first 3 digit to equal it  in decimal
  15.     mp["000"]=0 , mp["001"]=1 , mp["010"]=2 , mp["011"]=3,
  16.     mp["100"]=4 , mp["101"] =5 , mp["110"]= 6, mp["111"] =7;
  17.  
  18.     int idx =-1;
  19.     for(int i = 0; i < num.size() ; i++){
  20.         if(num[i]=='.'){
  21.             idx = i;
  22.             break;
  23.         }
  24.     }
  25.  
  26.         string temp; // contain the part before floating point
  27.  
  28.         if(idx ==-1) // no floating point
  29.              temp = num ;
  30.         else
  31.             temp = num.substr(0 , idx);
  32.  
  33.  
  34.         string ans="";
  35.  
  36.         int mod = int(temp.size()) % 3;
  37.         if(mod){
  38.             mod = 3- mod;
  39.             while(mod--) ans+='0';
  40.         }
  41.  
  42.         ans+= temp;
  43.  
  44.         string result ="";
  45.         for(int i=0 ; i < ans.size() ; i+=3){
  46.             string st = ans.substr(i , 3);
  47.             result+= '0'+ mp[st];
  48.         }
  49.  
  50.    if(idx!=-1){ // contain floating point
  51.  
  52.         result+='.';
  53.  
  54.         string point= num.substr(idx+1);
  55.  
  56.         int mod2= int (point.size())% 3 ;
  57.         if(mod2){
  58.             mod2= 3- mod2 ;
  59.             while(mod2--) point +='0';
  60.         }
  61.  
  62.         for(int i=0 ; i < point.size() ; i+=3){
  63.             string st2 = point.substr(i , 3);
  64.             result+= '0'+ mp[st2];
  65.         }
  66.     }
  67.  
  68.     cout <<"octal number : " << result << nl;
  69.  
  70. }
  71. int main() {
  72.  
  73.  
  74.     binToOctal();
  75.  
  76.     return 0;
  77. }
  78.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement