Advertisement
fahimkamal63

Swap two nibbles

May 2nd, 2019
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.11 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. vector<int> dec_to_binary(int x){
  5.     vector<int> binary;
  6.     int count = 8;
  7.     while(count--){
  8.         int k = x % 2;
  9.         binary.push_back(k);
  10.         x /= 2;
  11.     }
  12.     return binary;
  13. }
  14.  
  15. vector<int> change(vector<int> &binary){
  16.     swap(binary[0], binary[4]);
  17.     swap(binary[1], binary[5]);
  18.     swap(binary[2], binary[6]);
  19.     swap(binary[3], binary[7]);
  20. }
  21.  
  22. void show_binary(vector<int> binary){
  23.     for(int i = binary.size()-1; i > -1; i--){
  24.         cout << binary[i];
  25.     }
  26.     cout << endl;
  27. }
  28.  
  29. int binary_to_decimal(vector<int> binary){
  30.     int base = 1, decimal = 0;
  31.     for(int i = 0; i < binary.size(); i++){
  32.         int k = binary[i] * base;
  33.         decimal += k;
  34.         base *= 2;
  35.     }
  36.     return decimal;
  37. }
  38.  
  39. int main(){
  40.     int t; cin >> t;
  41.     while(t--){
  42.         int x; cin >> x;
  43.         vector<int> binary = dec_to_binary(x);
  44.  
  45.         //  Showing the binary form
  46.         show_binary(binary);
  47.         //  Swapping two nibbles
  48.         change(binary);
  49.         show_binary(binary);
  50.         int decimal = binary_to_decimal(binary);
  51.         cout << decimal << endl;
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement