#include<iostream>
#include <bitset>
using namespace std;
//以二进制打印(8位)
void print_binary(int a){
cout<<bitset<8>(a)<<endl;
}
//num表示第几个字节,从0开始
//start表示第几位开始,0-8
//length表示取得长度
int read_byte(char *a,int num,int start,int length){
if(length<8){
int temp; //用于返回的int
unsigned char temp1; //用于保存这个字节的char
temp1=a[num];
if(start==1){//当在当前字节中起始位置为第一位,只需取length长度,直接右移
temp1=temp1>>(8-length);
temp=temp1;
return temp;
}
else{ //当起始位置不是第一位时
temp1=temp1<<(start-1); //先左移动 如第二位开始需要移动2-1位
temp1=temp1>>(8-length);//在右移,如从第2位开始长度为3,
temp=temp1;
return temp;
}
}
else if(length==8){
int temp;
unsigned char temp1;
unsigned char temp2;
unsigned char temp3;
temp1=a[num];
if(start==1){
temp=temp1;
return temp;
}
else{
temp1=temp1<<(start-1);
temp2=a[num+1];
temp2=temp2>>(8-start+1);
temp3=temp1|temp2;
temp=temp3;
return temp;
}
}
else{
if(length>32){
return 0; //如果数据超过缓存区的长度,返回错误
}
if((num+length/8)>6){ //如果取出的数据超长,返回错误
return 0;
}
int temp;
int numof8;
int restof8;
unsigned char temp1;
unsigned char temp2;
temp1=a[num]; //存储某个起始字节的数据
// numof8=(length-start)/8; //查看跨度为多少字节
// restof8=length%8; //查看多出多少数据
if(start==1){ //这部分没写完
numof8=length/8;
int ss=temp1;
int i=1;
while(numof8>1){
ss=ss<<8;
ss=ss|a[num+i];
i++;
numof8--;
}
restof8=length%8;
ss=ss<<restof8;
temp2=a[num+i];
temp2=temp2>>(8-restof8);
ss=ss|temp2;
return ss;
}
else
{
}
}
}
int main(){
char data[6]={
79,85,130,248,47,200
};
cout <<"the array is:"<<endl;
for(int i=0;i<6;i++){
print_binary(data[i]);
}
cout<<"调用函数的方法:"<<endl;
int s1=read_byte(data,1,1,20);
cout <<s1<<endl;
print_binary(s1);
cout<<bitset<32>(s1)<<endl;
// long int s2=0;
// cout<<bitset<48>(s2)<<endl;
return 0;
}
【C++】C++位运算(使用移位运算符)
猜你喜欢
转载自blog.csdn.net/toby1123yjh/article/details/80966537
今日推荐
周排行