移位运算——获取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 <bitset>

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

 

  • 2
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值