#include <iostream>
#include <arpa/inet.h>
#include <string.h>
using namespace std;
union NumBit{
int num;
char bit[4];
};
//检验位数:如(默认需要一个位来作为符号位的标志)
//正数 1,用二进制表示为0000 0001,因此可知它所占用的位数为2
//正数 3, 用二进制表示为0000 0011,因此可知它所占用的位数为3
//负数 -1,用二进制表示为1111 1111 1111 1111 1111 1111 1111 1111,由此可知它所占用的位数为 2,因为前面都是用1来填充,是负数的特点
//用于检验这个正数所含有的位数(包含符号位)
int checkPosNum(const int a);
//用于检验这个负数所含有的位数(包含符号位)
int checkNegNum(const int a);
//检验数字
int checkNum(const int a)
{
if(a > 0)
{
checkPosNum(a);
}else
{
checkNegNum(a);
}
}
int checkPosNum(const int a)
{
NumBit nb;
int bitPos = 0;
int checkNum;
nb.num = a;
for(int i = 3; i >= 0; i--)
{
if(nb.bit[i] == 0)
{
continue;
}
if(nb.bit[i] > 0)
{
checkNum = 1;
bitPos = 1;
while(true)
{
checkNum *= 2;
bitPos++;
if(nb.bit[i] < checkNum)
{
return bitPos + 8 * i;
}
}
}
}
}
int checkNegNum(const int a)
{
NumBit nb;
int bitPos = 0;
int checkNum;
nb.num = a;
for(int i = 3; i >= 0; i--)
{
if(nb.bit[i] == -1)
{
continue;
}
if(nb.bit[i] < -1)
{
checkNum = -1;
bitPos = 1;
while(true)
{
checkNum *= 2;
bitPos++;
if(nb.bit[i] > checkNum)
{
return bitPos + 8 * i;
}
}
}
}
}
//获得这个数字所需要的字节数,例:如一个数,多余一个字节而不够两个字节则可用二个字节表示
int getBytes(const int a)
{
int b = 4 * a + 5;
int i = b / 8;
int j = b % 8;
if(j != 0)
return i + 1;
else
return i;
}
int writeRECT(unsigned char *rect,int bytes,int maxNum, int a[], int b[])
{
int numflag = 0;
int byteflag = 5;
int byteNum = 0;
rect[0] = rect[0] | ((unsigned char)maxNum << 3);
for(int i = 0; i < 4; i++)
{
numflag = byteflag % 8;
byteNum = byteflag / 8;
unsigned temp = (unsigned int)(a[i] << (32 - maxNum)) >> numflag;
*(unsigned int *)(rect + byteNum) = (*(unsigned int *)(rect + byteNum) << 24) | temp;
*(unsigned int *)(rect + byteNum) = ntohl(*(unsigned int *)(rect + byteNum));
byteflag += maxNum;
}
}
int main()
{
cout << "positive num" << endl;
cout << checkNum(10)<< endl;
cout << checkNum(100)<< endl;
cout << checkNum(100000000) << endl;
cout << checkNum(1000000000) << endl;
cout << "negative num" << endl;
cout << checkNum(-10)<< endl;
cout << checkNum(-100)<< endl;
cout << checkNum(-100000000)<< endl;
cout << checkNum(-1000000000)<< endl;
cout << "enter the four number for a Rect" << endl;
int a[4];
int i;
for(i = 0; i < 4; i++)
{
cin >> a[i];
}
if(a[0] > a[1] || a[2] > a[3])
{
cout<< "the numbers are unvalid, is like Xmin,Xmax,Ymin,Ymax"<<endl;
}
/*
a[0] = -450;
a[1] = 490;
a[2] = -611;
a[3] = 543;
*/
int b[4] = {0};
int maxNum = 0;
for(i = 0; i < 4; i++)
{
b[i] = checkNum(a[i]);
if(b[i] > 31)
{
cout << "the a[" << i << "] is too big"<<endl;
}
if(b[i] > maxNum)
{
maxNum = b[i];
}
}
int bytes = getBytes(maxNum);
unsigned char rect[bytes];
bzero(rect, sizeof(rect));
writeRECT(rect, bytes, maxNum, a, b);
cout << rect << endl;
}