日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C/C++?左移<<,?右移>>的作用及說明_C 語言

作者:慕木子 ? 更新時間: 2022-09-15 編程語言

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++ 左移右移越界情況

左移越界

  • 一個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();
}

輸出:

右移越界

右移越界,移出去的位都會變成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();
}

輸出:

原文鏈接:https://blog.csdn.net/MumuziD/article/details/109161095

欄目分類
最近更新