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
1
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);
Frithurik Grint is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
If you have data stored as an uint8_t array(in little Endian) like this:
uint8_t data[12]= { 0xe8, 0x03, 0x00, 0x00, 0xe9, 0x03, 0x00, 0x00, 0xea, 0x03, 0x00, 0x00}; // 3 uint32_t value (in little endian) of 1000, 1001, and 1002
All you need is to pointing to the right location and retrieve the data as uint32_t with pointer to the location and deference it.
uint8_t data[12]= { 0xe8, 0x03, 0x00, 0x00, 0xe9, 0x03, 0, 0, 0xea, 0x03, 0, 0};
int idx = 1; // get the second uint32_t value which is 1001 (0x000003e9)
uint32_t data1 = *(uint32_t*) &data[idx * 4];
2