我重新写了一个 ---------------------------- // Shift.cpp : Defines the entry point for the console application. //#include "stdafx.h" #include "iostream.h" struct ExtentInt { int low; int high; };int main(int argc, char* argv[]) { int x,y; ExtentInt temp; cout<<"Please input the high number:"; cin>>x; cout<<endl; cout<<"Please input the low number:"; cin >>y; temp.high=x; temp.low=y; char *pchar=(char*)&temp; int size=sizeof(ExtentInt)*8; for(int i=size-1;i>-1;i--)//因为结构体从低位存起 { char *begin=(pchar+i/8);//得到起始字节地址 char mask=1<<(i%8); char ch=(*begin)&mask; while(ch>1) ch/=2;//convert it to int :0,1 cout <<size-i <<" bit is : "<<int(ch)<<endl; } return 0; }
更正:因该使用unsigned char 否则会出现-128 --------------- // Shift.cpp : Defines the entry point for the console application. //#include "stdafx.h" #include "iostream.h" struct ExtentInt { int low; int high; };int main(int argc, char* argv[]) { int x,y; ExtentInt temp; cout<<"Please input the high number:"; cin>>x; cout<<endl; cout<<"Please input the low number:"; cin >>y; temp.high=x; temp.low=y; unsigned char *pchar=(unsigned char*)&temp; int size=sizeof(ExtentInt)*8; for(int i=size-1;i>-1;i--)//因为结构体从低位存起 { unsigned char *begin=(pchar+i/8);//得到起始字节地址 unsigned char mask=1<<(i%8); unsigned char ch=(*begin)&mask; while(ch>1) ch/=2;//convert it to int :0,1 cout <<size-i <<" bit is : "<<int(ch)<<endl; } return 0; }
-------------------------
char *pchar=(char*)pData;
//假设得到距离首位的n位的bit,首位为0位基数
char *begin=(pchar+n/8);//得到起始字节地址
char mask=128>>(n%8);
char ch=(*begin)&mask;
----------------------------
// Shift.cpp : Defines the entry point for the console application.
//#include "stdafx.h"
#include "iostream.h"
struct ExtentInt
{
int low;
int high;
};int main(int argc, char* argv[])
{
int x,y;
ExtentInt temp;
cout<<"Please input the high number:";
cin>>x;
cout<<endl;
cout<<"Please input the low number:";
cin >>y; temp.high=x;
temp.low=y; char *pchar=(char*)&temp;
int size=sizeof(ExtentInt)*8; for(int i=size-1;i>-1;i--)//因为结构体从低位存起
{
char *begin=(pchar+i/8);//得到起始字节地址
char mask=1<<(i%8);
char ch=(*begin)&mask;
while(ch>1)
ch/=2;//convert it to int :0,1
cout <<size-i <<" bit is : "<<int(ch)<<endl;
} return 0;
}
---------------
// Shift.cpp : Defines the entry point for the console application.
//#include "stdafx.h"
#include "iostream.h"
struct ExtentInt
{
int low;
int high;
};int main(int argc, char* argv[])
{
int x,y;
ExtentInt temp;
cout<<"Please input the high number:";
cin>>x;
cout<<endl;
cout<<"Please input the low number:";
cin >>y; temp.high=x;
temp.low=y; unsigned char *pchar=(unsigned char*)&temp;
int size=sizeof(ExtentInt)*8; for(int i=size-1;i>-1;i--)//因为结构体从低位存起
{
unsigned char *begin=(pchar+i/8);//得到起始字节地址
unsigned char mask=1<<(i%8);
unsigned char ch=(*begin)&mask;
while(ch>1)
ch/=2;//convert it to int :0,1
cout <<size-i <<" bit is : "<<int(ch)<<endl;
} return 0;
}