C++ -- 移位运算:获取unsigned short的高八位和低八位数值

示例代码:

#include "pch.h"
#include <iostream>
#include <string>

typedef  unsigned char  BYTE;
typedef  unsigned short WORD;
typedef  unsigned int   UINT32;
using namespace std;
int main()
{
string s ;
char str[100] = "hello,worl------------------------------d" ;
WORD word = 0x1234;
BYTE b1 =(BYTE) (word &0xff );//低八位
BYTE b2 = (BYTE)(word << 8);//低八位
BYTE b3 = (BYTE)(word >> 8);//高八位
cout << "b1=" <<hex<< b1+0 << endl;
cout << "b2=" <<hex<< b2+0 << endl;
cout << "b3=" << hex << b3 + 0 << endl;

getchar();

return 0;
}

将WORD强制类型转换为BYTE,默认取BYTE低八位的数值作为BYTE的值

0x1234&0xff 是0x0034 取低八位 所以b1是0x34

0x1234<<8 左移8位 是0x3400 取低八位 所以b2是0x00,即0

0x1245>>8,右移8位 是0x0012 取低8位 所以b3是0x12

将占用长度大的类型强制转换为长度较小的类型,默认取低位值作为长度较小的类型的值

补充:(循环移位)

循环左移n位: (x>>(N - n) ) | (x<<n);

循环右移n位: (x<<(N - n) ) | (x>>n)。

cout << "b1=" << (int)b1 << endl;//这样输出,不+0

--#include
--cout << "b3="<<bitset<sizeof(int)*8>(b3)<< endl;//二进制输出

https://blog.csdn.net/qq_36616692/article/details/88015908?utm_medium=distribute.pc_relevant_bbs_down.none-task-blog-baidujs-2.nonecase&depth_1-utm_source=distribute.pc_relevant_bbs_down.none-task-blog-baidujs-2.nonecase

posted @ 2021-01-21 10:03  手磨咖啡  阅读(1680)  评论(0编辑  收藏  举报