Search code examples
objective-carraysnsdataint32

How to get 4 bytes of data (uint8_t) into a variable of type uint32_t


I've been working with Cypress BLE PSoC 4200, and I've set up my GATT database to send int32 data packets to my iPhone. However, you can only write to the GATT database with uint8 pieces of data. So I wrote the following to take this int32 voltage reading and put it into a uint8 byte array:

    // function passes in int32 variable 'result'
    uint8 array[4];
    array[0] = result & 0xFF;
    array[1] = (result >> 8) & 0xFF;
    array[2] = (result >> 16) & 0xFF;
    array[3] = (result >> 24) & 0xFF;

So, given that in mind, when that int32 packet gets sent, I want to be able take each byte, and recombine them somehow into the original int32 value, and print it to the screen (e.g. 456000 will be 0.456 V).

Right now, I obtain the 4 bytes and handle them like such:

    NSData* data = [characteristic value];
    const uint8_t *reportData = [data bytes];

    // variable to hold the eventual 32-bit data
    uint32_t voltage = 0;

Is there a way to go through each index of *reportData and concatenate the bytes? Any help will do, thanks.


Solution

  • Would something like this not work?

    uint32_t v0 = (uint32_t)reportData[0];
    uint32_t v1 = (uint32_t)reportData[1] << 8;
    uint32_t v2 = (uint32_t)reportData[2] << 16;
    uint32_t v3 = (uint32_t)reportData[3] << 24;
    
    uint32_t voltage = v0 | v1 | v2 | v3;