Open
Description
Here's one you might like! It's endian agnostic since it reads or writes one byte at the time. The underlying CPU architecture handles endianness within the bitshift operators. No need for byteswap stuff. I use these functions all the time. Very copy + pasteable.
#ifdef _WIN32
# define TINYBITS_RESTRICT __restrict
#else
# define TINYBITS_RESTRICT __restrict__
#endif
#include <stdint.h>
inline uint8_t read_uint8(const uint8_t** TINYBITS_RESTRICT p)
{
uint8_t value = **p;
++(*p);
return value;
}
inline uint32_t read_uint32(const uint8_t** TINYBITS_RESTRICT p)
{
uint32_t value;
value = (*p)[0];
value |= (((uint32_t)((*p)[1])) << 8);
value |= (((uint32_t)((*p)[2])) << 16);
value |= (((uint32_t)((*p)[3])) << 24);
*p += 4;
return value;
}
inline float read_float(const uint8_t** TINYBITS_RESTRICT p)
{
union
{
uint32_t auint32;
float afloat;
} val;
val.auint32 = read_uint32(p);
return val.afloat;
}
inline v3 read_v3(const uint8_t** TINYBITS_RESTRICT p)
{
float x = read_float(p);
float y = read_float(p);
float z = read_float(p);
return v3(x, y, z);
}
void read_fourcc(const uint8_t** TINYBITS_RESTRICT p, uint8_t* TINYBITS_RESTRICT fourcc)
{
fourcc[0] = read_uint8(p);
fourcc[1] = read_uint8(p);
fourcc[2] = read_uint8(p);
fourcc[3] = read_uint8(p);
}
inline void write_uint8(uint8_t** TINYBITS_RESTRICT p, uint8_t value)
{
**p = value;
++(*p);
}
inline void write_uint32(uint8_t** TINYBITS_RESTRICT p, uint32_t value)
{
(*p)[0] = value & 0xFF;
(*p)[1] = (value >> 8 ) & 0xFF;
(*p)[2] = (value >> 16) & 0xFF;
(*p)[3] = value >> 24;
*p += 4;
}
inline void write_float(uint8_t** TINYBITS_RESTRICT p, float value)
{
union
{
uint32_t auint32;
float afloat;
} val;
val.afloat = value;
write_uint32(p, val.auint32);
}
inline void write_v3(uint8_t** TINYBITS_RESTRICT p, v3 value)
{
write_float(p, value.x());
write_float(p, value.y());
write_float(p, value.z());
}
inline void write_fourcc(uint8_t** TINYBITS_RESTRICT p, const char* TINYBITS_RESTRICT fourcc)
{
write_uint8(p, fourcc[0]);
write_uint8(p, fourcc[1]);
write_uint8(p, fourcc[2]);
write_uint8(p, fourcc[3]);
}
Metadata
Metadata
Assignees
Labels
No labels