Question

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) 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.

Was it helpful?

Solution

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top