Advertisement
Guest User

Untitled

a guest
Nov 25th, 2015
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <conio.h>
  4. #include <cstdlib>
  5. using namespace std;
  6.  
  7. void print_bits (unsigned n)
  8. {
  9.     int bit;
  10.     for (bit = sizeof(n)*8-1; bit >= 0; bit--)
  11.    
  12.     {
  13.         if ((n >> bit) & 01)
  14.         {
  15.             putchar ('1');
  16.         }
  17.         else
  18.         {
  19.             putchar ('0');
  20.         }
  21.        
  22.         if (bit % 4 == 0) putchar (' ');
  23.     }
  24.     cout<<endl;
  25. }
  26. unsigned replace_bits (unsigned x, unsigned p, unsigned n)
  27. {
  28.     unsigned mnoj=0, z;
  29.     int bit;
  30.     for (bit = sizeof(n)*8-1; bit >= 0; bit--)
  31.     {
  32.         if (bit>=p && bit<p+n)
  33.         {
  34.             z=((~(x>>bit) & 01));
  35.             mnoj=(mnoj<<1) | z;
  36.         }
  37.         else
  38.         {
  39.             z=(((x>>bit) & 01));
  40.             mnoj=(mnoj<<1) | z;
  41.         }
  42.     }
  43.     cout<<endl;
  44.     return mnoj;
  45. }
  46. main ()
  47. {
  48.     unsigned num;
  49.     cout << "Input X" << endl;
  50.     cin >> num;
  51.     print_bits (num);
  52.     int n,p;
  53.     do
  54.     {
  55.         cout << " Enter P [numeracia s nula]: " ;
  56.         cin >> p;
  57.         if (p<0) {cout<<" -> ERROR : P must be >=0"<<endl;}
  58.        
  59.     } while (p<0);
  60.    
  61.     do
  62.     {
  63.         cout << " Enter N : " ;
  64.         cin >> n;
  65.         if (n<=0) {cout<<" -> ERROR : N must be >=1"<<endl;}
  66.        
  67.     } while (n<=0);
  68.    
  69.    
  70.    
  71.     unsigned result = replace_bits (num,p,n);
  72.     print_bits (result);
  73.     system ("PAUSE");
  74.     return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement