开发者

Reading n-bits from a 32bit chunk

I am trying to read a binary file written by an legacy Fortan application.

It writes data into chunks of 32bit. Some of these 32bit chnuk contains mutiple data.

e.g 1 : 9 bit will contain position offset value ranging from (0-511) 22 bit will contain data record value ranging from (1-2097151)

e.g.2 : 17 bit will contain year value ranging from (1-131071) 4 bit will contain month value ranging from (1-12) 5 bit will contain day value ranging from (1-31开发者_Python百科) 5 bit will contain hour value ranging from (1-24)

I am wondering how to read the data, I can get the 32bit value store in integer, but what operations should I perform to extract the different parts of that 4byte value.


Generally speaking, something like the following (which is not necessarily valid C#) should work:

int readValue(int sourceBits, int dataOffset, int dataLength) {
    unsigned int mask = pow(2, dataLength) - 1;
    return (sourceBits >> dataOffset) & mask;
}

Note that the data offset is treated as beginning from the rightmost bit in the field, with values growing to the left. To use offsets that begin from the left and grow to the right, do something like:

int readValue(int sourceBits, int dataOffset, int dataLength) {
    unsigned int mask = pow(2, dataLength) - 1;
    return (sourceBits >> (32 - (dataOffset - dataLength))) & mask;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜