I have something like this:
Code:
struct State{
unsigned char *buf;
}
I want to read/write values from the buffer in chunks of 8, 16, and 32 bits.
This is the code I have come up with (which I would like someone to critique)
Code:
/* basically read the values from the last backwards */
static uint32_t read(State *s, size_t offset, size_t size)
{
ssize_t i;
uint32_t ret;
if(!size){
return 0;
}
ret = s->buf[offset + size - 1];
for(i = size - 2; i >= 0; i--)
{
ret <<= 8;
ret |= s->buf[offset + i];
}
return ret;
}
/* write the value from the first */
static void write(State *s, size_t offset, uint32_t val){
size_t i;
for (i = 0; i < size; i++)
{
s->buf[offset + i] = val & 0xff;
val >>= 8;
}
}
Ignoring the complication brought by the 'offset' part and assuming that 'i' indexes the array, is this the best way to do it ?