移位操作知识点

整数左移一位相当于将该数乘以2。编写一个函数:
unsigned power2( unsigned number, unsigned pow );使用移位运算计算number*2pow,并以整数形式输出计算结果。注意考虑数据的溢出。

#include<iostream>
using namespace std;
unsigned power2(unsigned number,unsigned pow)
{
    
    
    unsigned c=1;
    unsigned bitmask=1<<31;
    while(c<31) //溢出判断
    {
    
    
        if(number&bitmask)
            break; //查找最高位的1
        c++;
        bitmask>>=1;
    }
    if(pow<c)
        return number<<pow;
    else {
    
    
        cout<<"overflow!\n";
        return 0;

    }
}
int main()
{
    
    
    int n,p;
    cin>>n>>p;
    cout<<power2(n,p);
    return 0;
}

编写程序,将一个整型变量右移4位,并以二进制数形式输出该整数在移位前和移位后的数值。观察系统填补空缺的数位情况。

#include<iostream>
using namespace std;
void bitDisplay(unsigned value);
int main()
{
    
    
    unsigned x;
    cout << "Enter an unsigned integer: ";
    cin >> x;
    bitDisplay(x);
    x>>=4;
    cout<<"Right 4-bit\n";
    bitDisplay(x);
}
void bitDisplay(unsigned value)
{
    
    
    unsigned c;
    unsigned bitmask = 1<<31;
    cout << value << " = \t";
    for( c=1; c<=32; c++ )
    {
    
    
        cout << ( value&bitmask ? '1' : '0' );
        value <<= 1;
        if( c%8 == 0 )
            cout << ' ';
    }
    cout << endl;
}

在这里插入图片描述

#include<iostream>
using namespace std;

int main()
{
    
    
    int i, c;
    cin>>c;
    unsigned int bitmask = 1<<31;
    cout << c << " = \t";
    for( i=1; i<=32; i++ )    {
    
    
        cout << ( c&bitmask ? '1' : '0' );
        bitmask >>= 1;
        if( i%8 == 0 )
            cout << ' ';
    }
    cout << endl;

}

猜你喜欢

转载自blog.csdn.net/weixin_51443397/article/details/114590136