Search code examples
carduino-esp32

Int32's from byte stream


I have a byte stream like

uint8_t buf[] = { 0xFF, 0x1B, … , 0x34 }; // approx. 800 Bytes

Now, I want to extract various ints from known positions and store them in their own variables, like "get int64 from index 0x3B of buffer" or "get uint32 from index 0x03".

What's the best way to do?

The stream is big endian, but I could use a byteswap (bswap64()) from ESP32 headers


Solution

  • There are several ways to convert a number of bytes into a fixed-size integer, one of them is:

    #include <stdlib.h>
    #include <stdint.h>
    
    static size_t get_integer(uint8_t *buf, size_t start, size_t count)
    {
        size_t i, result = 0;
    
        for (i = 0; i < count; i++)
            result |= (size_t)buf[i] << ((count - i - 1) * CHAR_BIT);
    
        return result;
    }
    
    
    int main()
    {
        uint8_t buf[] = { 0x00, 0x00, 0x01, 0x00, 0x32, 0x34, 0x23, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00 };
    
        int r1 = (int)get_integer(buf, 0, sizeof(int));
        long r2 = (long long)get_integer(buf, 8, sizeof(long long));
    }
    

    using a function to convert. The other is less safe and consists to cast a pointer and put its value directly into an integer variable:

    int r1 = *(int *)(buf + 0);     // where 0 and 12 are the beginning positions
    long r2 = *(long *)(buf + 12);