1f3922f8c25a45f77ef7ff4c6958529d75c9ecb3
[paraslash.git] / portable_io.h
1 static inline uint64_t read_portable(unsigned bits, const char *buf)
2 {
3 uint64_t ret = 0;
4 int i, num_bytes = bits / 8;
5
6 for (i = 0; i < num_bytes; i++) {
7 unsigned char c = buf[i];
8 ret += ((uint64_t)c << (8 * i));
9 }
10 return ret;
11 }
12
13 static inline uint64_t read_u64(const char *buf)
14 {
15 return read_portable(64, buf);
16 }
17
18 static inline uint32_t read_u32(const char *buf)
19 {
20 return read_portable(32, buf);
21 }
22
23 static inline uint16_t read_u16(const char *buf)
24 {
25 return read_portable(16, buf);
26 }
27
28 static inline uint8_t read_u8(const char *buf)
29 {
30 return read_portable(8, buf);
31 }
32
33 static inline void write_portable(unsigned bits, char *buf, uint64_t val)
34 {
35 int i, num_bytes = bits / 8;
36 // fprintf(stderr, "val: %lu\n", val);
37 for (i = 0; i < num_bytes; i++) {
38 buf[i] = val & 0xff;
39 // fprintf(stderr, "buf[%d]=%x\n", i, buf[i]);
40 val = val >> 8;
41 }
42 }
43
44 static inline void write_u64(char *buf, uint64_t val)
45 {
46 write_portable(64, buf, val);
47 }
48
49 static inline void write_u32(char *buf, uint32_t val)
50 {
51 write_portable(32, buf, (uint64_t) val);
52 }
53
54 static inline void write_u16(char *buf, uint16_t val)
55 {
56 write_portable(16, buf, (uint64_t) val);
57 }
58
59 static inline void write_u8(char *buf, uint8_t val)
60 {
61 write_portable(8, buf, (uint64_t) val);
62 }