網站首頁 編程語言 正文
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
相關推薦
- 2022-09-17 Redis請求處理的流程分析_Redis
- 2022-08-29 Python繪制散點圖之可視化神器pyecharts_python
- 2022-07-21 css實現水平居中和垂直居中,清除浮動
- 2023-02-10 Python常見錯誤:IndexError:?list?index?out?of?range解決_p
- 2023-02-18 C++中std::thread線程用法_C 語言
- 2022-08-30 C++逐步介紹日期類的使用_C 語言
- 2022-03-21 C++名稱空間介紹_C 語言
- 2022-06-12 C#自定義特性(Attribute)詳解_C#教程
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支