Getting different data types out of a char stream

12 Jan 2012

I have succesfully interfaced the Nordic nRF24L01+ chip to my mbed with the library. However, the data I am sending consists of a 8 16-bit numbers in each packet.

The packet I receive on the mbed from the nordic library is an array of chars. What is the best way to extract/reformat the data in this array so that I can retrieve my 16-bit unsigned numbers?

Thanks!

12 Jan 2012

Hi Carson,

Assuming the bytes are in the right order, you can cast it from an array of one type to the other.

#include "mbed.h"

int main() {
    // the input array
    char raw_inputs[16] = {0}; 

    // cast to unsignet 16-bit values
    uint16_t * nice_inputs = (uint16_t*)raw_inputs;

    for(int i=0; i<8; i++) {
        printf("nice_inputs[%d] = %d\n", i, nice_inputs[i]);
    }
}

If the bytes are in the "wrong" order (see endianness), you actually may have to do some more manual swizzling first; i.e. swap byte 0 and 1, 2 and 3, 4 and 5 etc before casting.

Hope that helps!

Simon

12 Jan 2012

Hey, This should do the trick, just make sure the raw_data stays in scope while using the reinterpreted pointer

uint8_t raw_data[8];

#pragma pack(push, 1) //make sure the structure is byte aligned
struct PacketData {
  uint16_t number1;
  uint16_t number2;
  uint16_t number3;
  uint16_t number4;
};
#pragma pack(pop) //disable single byte alignment

if( sizeof(PacketData) == sizeof(raw_data) ){ // if they're different sizes you could do bad things to your memory
  PacketData* decoded_values = reinterpret_cast<PacketData*>(raw_data);
  uint16_t value_one = decoded_values->number1; //you may need to invert the bytes if there transmitted in a different order
}

I'd written this before Simon replied but I'l post it anyway as it can be used on complex data packets with multiple types, and you can have nice names on the data feilds, its also the way I do it in my serial library so Simon's simpler solution didn't occur to me,

12 Jan 2012

Thanks Simon and Chris!