简体   繁体   中英

How do I decode repeating unsigned MSB and LSB 8-bit words?

I'm writing a module that accepts some data from a spectrometer via a serial port and needs to decode it. The spectral data is encoded as 512-bytes in repeating unsigned MSB and LSB 8-bit words according to the manual. How would I decode this in C/C++?

23 – 534 encoded as 512-bytes in repeating unsigned MSB and LSB 8-bit words [MSB]*256 + [LSB].

That's a snippet from the manual.

Okay, I'd like to add in another portion to this question. According to a comment below, this is in big-endian. Now, what I'm confused about it is that if it indeed is in big-endian, wouldn't conversion to little-endian be as simple as reversing the order of all the bytes? And if that is the case, then the output to that would essentially be something like... LSB5, MSB5, LSB4, MSB4, LSB3, MSB3, LSB2, MSB2, LSB1, MSB1 and so on, which could then be converted to 16-bit words. What is it that I'm going wrong with here?

Also, if this is indeed big-endian, aren't there any native (even platform-specific if necessary, but faster) methods to handle the conversion?

I'm an over-optimizer sometimes, so even though Fiddling Bits has provided a perfectly adequate solution, it has unneeded divides and unneeded branches. So I'll serve up a redundant answer here.

uint8_t byteArray[512];
uint16_t wordArray[256], word, byteIdx, wordIdx;

for (byteIdx=0, wordIdx=0; byteIdx < 511; )
{
    word = byteArray[byteIdx++] << 8;
    wordArray[wordIdx++] = word | byteArray[byteIdx++]
}

The key concept is to shift the MSB byte up 8 bits (x<<8 is equivalent to x*256) then or/add it to the LSB to form the 16-bit word. The rest is all index management.

You'd need to store the MSB and LSB into a single word. For example:

uint8_t msb, lsb;
uint16_t word;

word = (msb << 8) | lsb;

A loop of this would look something like this:

uint8_t byteArray[512];
uint16_t wordArray[256], byteArrIdx;

for(byteArrIdx = 0; byteArrIdx < 512; byteArrIdx++)
{
    if((byte % 2) == 0)
        wordArray[(byteArrIdx / 2)] = byteArray[byteArrIdx] << 8;
    else
        wordArray[(byteArrIdx / 2)] |= byteArray[byteArrIdx];
}

Note:

The output of msb << 8 and msb * 256 is identical. I prefer using bit shifting because your intentions are more clear to the reader.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM