1 #include "pch.h"
2 #include <iostream>
3 #include <string>
4
5 typedef unsigned char BYTE;
6 typedef unsigned short WORD;
7 typedef unsigned int UINT32;
8 using namespace std;
9 int main)
10 {
11 string s ;
12 char str[100] = "hello,worl------------------------------d" ;
13 WORD word = 0x1234;
14 BYTE b1 =BYTE) word &0xff );//低八位
15 BYTE b2 = BYTE)word << 8);//低八位
16 BYTE b3 = BYTE)word >> 8);//高八位
17 cout << "b1=" <<hex<< b1+0 << endl;
18 cout << "b2=" <<hex<< b2+0 << endl;
19 cout << "b3=" << hex << b3 + 0 << endl;
20
21
22 getchar);
23
24 return 0;
25 }
运行截图:
将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 <bitset>
cout << “b3=”<<bitset<sizeofint)*8>b3)<< endl;//二进制输出

