讀取一個integer on byte

#include <iostream>
#include <conio.h>	// for _getche
#include <limits>
using std::cin;
using std::cout;
using std::endl;
using std::hex;

int getByte( int x, int n)
{
	return ( x>>(n<<3)&0xff);		// 因為 右旋1個byte為8bit;右旋2個byte為16bit;右旋3個byte為24bit...
	                                        // 觀察知 右旋n個byte為8n個bit,是故 取 n << 3
}//end of getByte

void pause()
{
	cout << "Press any key to continue" << endl;	
	_getche();
	//getchar();
}//end of pause


int main(int argc, char*argv[])
{
	int i = 0x12345678;
	// for the first byte
	//      bit : 0001 0010 0011 0100 0101 0110 0111 1000
	//  &  )mask: 0000 0000 0000 0000 0000 0000 1111 1111
	// ---------------------------------------------------
	//      ret : 0000 0000 0000 0000 0000 0000 0111 1000 
    //      == 0x    0    0    0    0    0    0    7    8 

	// for the second byte
	//      bit : 0000 0000 0001 0010 0011 0100 0101 0110 
	//  &  )mask: 0000 0000 0000 0000 0000 0000 1111 1111
	// ---------------------------------------------------
	//      ret : 0000 0000 0000 0000 0000 0000 0111 1000 
	//      == 0x    0    0    0    0    0    0    5    6

	// for the third byte
	//      bit : 0000 0000 0000 0000 0001 0010 0011 0100
	//  &  )mask: 0000 0000 0000 0000 0000 0000 1111 1111
	// ---------------------------------------------------
	//      ret : 0000 0000 0000 0000 0000 0000 0011 0100 
	//      == 0x    0    0    0    0    0    0    3    4

	// for the fourth byte
	//      bit : 0000 0000 0000 0000 0000 0000 0001 0010
	//  &  )mask: 0000 0000 0000 0000 0000 0000 1111 1111
	// ---------------------------------------------------
	//      ret : 0000 0000 0000 0000 0000 0000 0011 0100 
	//      == 0x    0    0    0    0    0    0    1    2


	cout << "the first byte  : " <<  hex << getByte( i , 0 ) << endl;
	cout << "the second byte : " <<  hex << getByte( i , 1 ) << endl;
	cout << "the third byte  : " <<  hex << getByte( i , 2 ) << endl;
	cout << "the fourth byte : " <<  hex << getByte( i , 3 ) << endl;
	pause();
	return 0;
}//end of main


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值