Facebook
From Bulky Kangaroo, 2 Months ago, written in C++.
Embed
Download Paste or View Raw
Hits: 88
  1. #include <iostream>
  2. #include <climits>
  3. #include <cmath>
  4. using namespace std;
  5.  
  6. string DecToBin(int);
  7. unsigned short BinToDec(string);
  8. int main(int argc, const char * argv[]) {
  9.     unsigned short max = USHRT_MAX;
  10.     unsigned short input;
  11.     cout<<"Podaj liczbe: ";
  12.     cin>>input;
  13.     string bin = DecToBin(input);
  14.     int diff = 16-bin.length();
  15.     string wholeBin="";
  16.     for (int i = 0; i<diff; i++){
  17.         wholeBin+="0";
  18.     }
  19.     wholeBin+=bin;
  20.     cout<<"Binarnie:\t"<<wholeBin<<endl;
  21.  
  22.     string result;
  23.     for (int i = wholeBin.length()-1; i>=0; i--){
  24.         result+=wholeBin[i];
  25.     }
  26.     cout<<"Reverse:\t"<<result<<endl;
  27.     cout<<"Reverse decimal: "<<BinToDec(result);
  28. }
  29.  
  30. string DecToBin(int number)
  31. {
  32.     if ( number == 0 ) return "0";
  33.     if ( number == 1 ) return "1";
  34.  
  35.     if ( number % 2 == 0 )
  36.         return DecToBin(number / 2) + "0";
  37.     else
  38.         return DecToBin(number / 2) + "1";
  39. }
  40.  
  41. unsigned short BinToDec(string binary){
  42.     unsigned short result=0;
  43.     int index=0;
  44.     for (int i = binary.length()-1; i>=0; i--){
  45.         if (binary[i]!='0'){
  46.             result+=pow(2,index);
  47.         }
  48.         index++;
  49.     }
  50.     return result;
  51. }