软件编程
位置:首页>> 软件编程>> C语言>> C/C++ 左移<<, 右移>>的作用及说明

C/C++ 左移<<, 右移>>的作用及说明

作者:慕木子  发布时间:2021-12-30 01:42:59 

标签:C,C++,左移<<,右移>>

C/C++ 左移<<, 右移>>作用

1. 左移 <<

取两个数字,左移第一个操作数的位,第二个操作数决定要移动的位置。换句话说,左移动一个整数 x 和一个整数 y ( x < < y ) 等于 x 乘以 2y

代码示例:

/* C++ Program to demonstrate use of left shift  
  operator */
#include<stdio.h>
int main()
{
   // a = 5(00000101), b = 9(00001001)
   unsigned char a = 5, b = 9;  

// The result is 00001010  
   printf("a<<1 = %d\n", a<<1);

// The result is 00010010  
   printf("b<<1 = %d\n", b<<1);  
   return 0;
}

输出结果:

a<<1 = 10
b<<1 = 18

2. 右移 >>

取两个数字,向右移动第一个操作数的位,第二个操作数决定移动的位置。同样地,右平移( x > > y )等于x除以 2y.

代码示例:

/* C++ Program to demonstrate use of right
  shift operator */
#include<stdio.h>

using namespace std;
int main()
{
   // a = 5(00000101), b = 9(00001001)
   unsigned char a = 5, b = 9;  

// The result is 00000010  

printf("a>>1 = %d\n", a>>1);

// The result is 00000100
   printf("b>>1 = %d\n", b>>1);  
   return 0;
}

输出结果:

a>>1 = 2
b>>1 = 4

3. 数字 1 左移 <<

1 << i = 2i。它只适用于正数。

代码示例:

#include<stdio.h>
int main()
{  
  int i = 3;  
  printf("pow(2, %d) = %d\n", i, 1 << i);
  i = 4;  
  printf("pow(2, %d) = %d\n", i, 1 << i);
  return 0;
}

输出结果:

pow(2, 3) = 8
pow(2, 4) = 16

注意事项:

C/C++ 左移<<, 右移>>的作用及说明

C++ 左移右移越界情况

左移越界

  • 一个32位的long,值为1,

  • 左移32位 = 1

  • 左移33位= 2

  • ...

  • 左移64位= 1

  • 左移65位= 3

所以左移越界有点向循环左移,左移Index位--》相当于左移 Index%32位 ,当然%多少是根据变量类型来定的

int main() {

long v[2] = {0,0};
long u1 = 1;
long u2 = (u1 <<33);
v[1] |= (u1<<33);
LOG(sizeof(long))
cout << u1 <<"," <<u2<< "," << v[1]<< endl;
std::cin.get();
}

输出:

C/C++ 左移<<, 右移>>的作用及说明

右移越界

右移越界,移出去的位都会变成0

#include<iostream>
#include<vector>
#include<unordered_map>
using namespace std;
#define LOG(x) std::cout<<x<<std::endl;

int main() {

long v[2] = {0,0};
long u1 =3;
long u2 = (u1 >>1);
v[1] |= (u1>>1);
LOG(sizeof(long))
cout << u1 <<"," <<u2<< "," << v[1]<< endl;
std::cin.get();
}

输出:

C/C++ 左移<<, 右移>>的作用及说明

来源:https://blog.csdn.net/MumuziD/article/details/109161095

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com