您的位置:首页 > 其它

OJ 系列之字节流解析

2016-01-22 15:49 288 查看

1、问题描述

根据数值占用BIT数,按顺序从输入字节流中解析出对应数值,解析顺序按输入数组astElement索引升序。

/*
输入:

字节数组长度uiIutputLen为2;

字节数组aInputByte[2]为{0x62, 0x80},对应二进制为“01100010 1 000 0000”;

解析数值个数uiElementNum为2;

数值[0]的值占4个bit,即astElement[0].uiElementLength = 4;

数值[1]的值占5个bit,即astElement[1].uiElementLength = 5;

输出:

数值[0]的值为6,二进制为“0110”,即astElement[0].uiElementValue = 6;

数值[1]的值为5,二进制为“0010 1”,即astElement[1].uiElementValue = 5。

功能: 根据数值占用BIT数,按顺序从输入字节流中解析出对应数值,
解析顺序按输入数组astElement索引升序

输入:unsigned int uiIutputLen:字节数组(流)长度
unsigned char aInputByte:字节数组(流)
unsigned int uiElementNum:解析数值个数
ELEMENT_STRU astElement[]:数值的结构数组指针,含义如下
Struct {
unsigned int uiElementLength;   //表示uiElementValue占用BIT数,范围1~32
unsigned int uiElementValue;    //从字节流中按顺序解析的数值,用于输出
}ELEMENT_STRU;

输出:参见上述ELEMENT_STRU中uiElementValue描述

返回:void
*/


2、解题思路

根据数值占用BIT数,按顺序从输入字节流中解析出对应数值,因此第一步将整个数据转换成字节流来进行解析(本文处理成int型)。然后再对字节流进行解析处理。

3、代码实现

typedef struct {
unsigned int uiElementLength;   //表示数值uiElementValue占用BIT数,范围1~32
unsigned int uiElementValue;    //表示编码的数值
}ELEMENT_STRU;

void Decode(unsigned int uiIutputLen, unsigned char aInputByte[],
unsigned int uiElementNum, ELEMENT_STRU astElement[])
{

if(!aInputByte || !astElement)
return;
if(uiElementNum==0||uiIutputLen==0)
return;
/*其实可以存储成char,为了计算方便,
不考虑存储空间大小*/
vector<int> vec;

unsigned int i = 0;
unsigned int temp = 0;
int temp1 = 0x80;
unsigned int j = 0,k = 0;
int sum = 0;

int bittemp = 0;
/*将数据转成2进制数据存入int 数组中*/
for(i = 0;i<uiIutputLen;i++) {
temp = aInputByte[i];
for(j = 0;j<8;j++) {
//只要获取当前最高位和0x1000 0000 的与值
bittemp = (temp&temp1);
//0x1000 0000 或者0x0000 0000 右移动7位得到1或者0;
bittemp = (bittemp>>7);
/*当前数左移动1位*/
vec.push_back(bittemp);
temp = (temp<<1);
}
}
/*解析数值个数*/
int size = vec.size();
for(i=0;i<uiElementNum;i++) {
temp = 0;
for(j=0;j<astElement[i].uiElementLength;j++) {
if(astElement[i].uiElementLength<1 && \
astElement[i].uiElementLength>31)
return;
/*解析数值的总长度uiElementLength之和
大于vec的总长度,这里做截取处理*/
if(k>size) {
break;
}
temp = (temp<<1)+vec[k];
k++;

}
if(k>size&&temp!=0) {
astElement[i].uiElementValue = temp;
break;
} else if(k>size&&temp==0){
break;
}
astElement[i].uiElementValue = temp;
}

return;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  字节流解析