1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
/*
* Copyright (C) 2007-2009 Andre Noll <maan@tuebingen.mpg.de>
*
* Licensed under the GPL v2. For licencing details see COPYING.
*/
/** \file portable_io.h Inline functions for endian-independent binary IO. */
static inline uint64_t read_portable(unsigned bits, const char *buf)
{
uint64_t ret = 0;
int i, num_bytes = bits / 8;
for (i = 0; i < num_bytes; i++) {
unsigned char c = buf[i];
ret += ((uint64_t)c << (8 * i));
}
return ret;
}
static inline uint64_t read_u64(const char *buf)
{
return read_portable(64, buf);
}
static inline uint32_t read_u32(const char *buf)
{
return read_portable(32, buf);
}
static inline uint16_t read_u16(const char *buf)
{
return read_portable(16, buf);
}
static inline uint8_t read_u8(const char *buf)
{
return read_portable(8, buf);
}
static inline void write_portable(unsigned bits, char *buf, uint64_t val)
{
int i, num_bytes = bits / 8;
// fprintf(stderr, "val: %lu\n", val);
for (i = 0; i < num_bytes; i++) {
buf[i] = val & 0xff;
// fprintf(stderr, "buf[%d]=%x\n", i, buf[i]);
val = val >> 8;
}
}
static inline void write_u64(char *buf, uint64_t val)
{
write_portable(64, buf, val);
}
static inline void write_u32(char *buf, uint32_t val)
{
write_portable(32, buf, (uint64_t) val);
}
static inline void write_u16(char *buf, uint16_t val)
{
write_portable(16, buf, (uint64_t) val);
}
static inline void write_u8(char *buf, uint8_t val)
{
write_portable(8, buf, (uint64_t) val);
}
|