2 * Copyright (C) 2007-2009 Andre Noll <maan@tuebingen.mpg.de>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file portable_io.h Inline functions for endian-independent binary IO. */
9 static inline uint64_t read_portable(unsigned bits, const char *buf)
12 int i, num_bytes = bits / 8;
14 for (i = 0; i < num_bytes; i++) {
15 unsigned char c = buf[i];
16 ret += ((uint64_t)c << (8 * i));
21 static inline uint64_t read_u64(const char *buf)
23 return read_portable(64, buf);
26 static inline uint32_t read_u32(const char *buf)
28 return read_portable(32, buf);
31 static inline uint16_t read_u16(const char *buf)
33 return read_portable(16, buf);
36 static inline uint8_t read_u8(const char *buf)
38 return read_portable(8, buf);
41 static inline void write_portable(unsigned bits, char *buf, uint64_t val)
43 int i, num_bytes = bits / 8;
44 // fprintf(stderr, "val: %lu\n", val);
45 for (i = 0; i < num_bytes; i++) {
47 // fprintf(stderr, "buf[%d]=%x\n", i, buf[i]);
52 static inline void write_u64(char *buf, uint64_t val)
54 write_portable(64, buf, val);
57 static inline void write_u32(char *buf, uint32_t val)
59 write_portable(32, buf, (uint64_t) val);
62 static inline void write_u16(char *buf, uint16_t val)
64 write_portable(16, buf, (uint64_t) val);
67 static inline void write_u8(char *buf, uint8_t val)
69 write_portable(8, buf, (uint64_t) val);