2 * Copyright (C) 2007 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 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_portable_be(unsigned bits, const char *buf)
24 int i, num_bytes = bits / 8;
26 for (i = 0; i < num_bytes; i++) {
27 unsigned char c = buf[i];
28 ret += ((uint64_t)c << (8 * (num_bytes - i - 1)));
33 static inline uint64_t read_u64(const char *buf)
35 return read_portable(64, buf);
38 static inline uint32_t read_u32(const char *buf)
40 return read_portable(32, buf);
43 static inline uint16_t read_u16(const char *buf)
45 return read_portable(16, buf);
48 static inline uint8_t read_u8(const char *buf)
50 return read_portable(8, buf);
53 static inline uint64_t read_u64_be(const char *buf)
55 return read_portable_be(64, buf);
58 static inline uint32_t read_u32_be(const char *buf)
60 return read_portable_be(32, buf);
63 static inline uint16_t read_u16_be(const char *buf)
65 return read_portable_be(16, buf);
68 static inline void write_portable(unsigned bits, char *buf, uint64_t val)
70 int i, num_bytes = bits / 8;
71 for (i = 0; i < num_bytes; i++) {
77 static inline void write_portable_be(unsigned bits, char *buf, uint64_t val)
79 int i, num_bytes = bits / 8;
80 for (i = 0; i < num_bytes; i++) {
81 buf[num_bytes - i - 1] = val & 0xff;
86 static inline void write_u64(char *buf, uint64_t val)
88 write_portable(64, buf, val);
91 static inline void write_u32(char *buf, uint32_t val)
93 write_portable(32, buf, (uint64_t) val);
96 static inline void write_u16(char *buf, uint16_t val)
98 write_portable(16, buf, (uint64_t) val);
101 static inline void write_u8(char *buf, uint8_t val)
103 write_portable(8, buf, (uint64_t) val);
106 static inline void write_u64_be(char *buf, uint64_t val)
108 write_portable_be(64, buf, val);
111 static inline void write_u32_be(char *buf, uint32_t val)
113 write_portable_be(32, buf, (uint64_t) val);
116 static inline void write_u16_be(char *buf, uint16_t val)
118 write_portable_be(16, buf, (uint64_t) val);