#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
讀取一個integer on byte
最新推荐文章于 2021-12-01 00:28:06 发布