Pella86

Bin string

Feb 3rd, 2019
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.13 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <bitset>
  4. #include <cmath>
  5. #include <vector>
  6.  
  7. using namespace std;
  8.  
  9. const int BIT_LEN = 4;
  10.  
  11. string conStrBin(string s){
  12.     string dest;
  13.     for(int i = 0; i < s.size(); i++){
  14.         dest += bitset<8>(s[i]).to_string();
  15.     }
  16.     return dest;
  17. }
  18.  
  19. int bintoDec(string binstr, int istart){
  20.     int tmp = 0;
  21.     int iend = istart + BIT_LEN;
  22.  
  23.     for(int i = istart; i < iend; i++){
  24.         int vi = binstr[i] - 48;
  25.         int exponent = i - istart;
  26.         int val = vi * pow(2, (BIT_LEN - 1) - exponent );
  27.         tmp += val;
  28.     }
  29.  
  30.     return tmp;
  31. }
  32.  
  33. int main(int argc, char** argv){
  34.  
  35.     string input_string;
  36.     cout<<"WORD : ";
  37.     cin>>input_string;
  38.  
  39.     string bin_string = conStrBin(input_string);
  40.     cout<< "BIN : " << bin_string << endl;
  41.  
  42.     int v_result_size = bin_string.size() / BIT_LEN;
  43.     vector<int> v_result(v_result_size);
  44.  
  45.     for(int i = 0; i < v_result_size; i++){
  46.       v_result[i] = bintoDec(bin_string, i * BIT_LEN);
  47.     }
  48.  
  49.     cout<<endl;
  50.  
  51.     for(int i=0; i < v_result_size; i++){
  52.         cout<< "-" << v_result[i] << "-";
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment