示例代碼:
#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;//二進制輸出