-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbinaryio.c
87 lines (66 loc) · 1.94 KB
/
binaryio.c
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <stdio.h>
/**
Portable binary integer read routines
Portable binary integer read routines are slightly tricky to
write. ANSI C guarantees that an int shall have at least 16 bits
and a long at least 32 bits, but not that CHAR_BIT (the number
of bits ina byte) shall be 8.
The routines assume that the filesystem reads back binary files in
bytes of 8 bits when written to in bytes of 8 bits.
*/
/**
Get a 16-bit big-endian signed integer from a stream.
Does not break, regardless of host integer representation.
@param[in] fp - pointer to a stream opened for reading in binary mode
@ returns the 16 bit value as an integer
*/
int fget16be(FILE *fp)
{
int c1, c2;
c2 = fgetc(fp);
c1 = fgetc(fp);
return ((c2 ^ 128) - 128) * 256 + c1;
}
/**
Get a 32-bit big-endian signed integer from a stream.
Does not break, regardless of host integer representation.
@param[in] fp - pointer to a stream opened for reading in binary mode
@ returns the 32 bit value as a long
*/
long fget32be(FILE *fp)
{
int c1, c2, c3, c4;
c4 = fgetc(fp);
c3 = fgetc(fp);
c2 = fgetc(fp);
c1 = fgetc(fp);
return ((c4 ^ 128) - 128) * 256 * 256 * 256 + c3 * 256 * 256 + c2 * 256 + c1;
}
/**
Get a 16-bit little-endian signed integer from a stream.
Does not break, regardless of host integer representation.
@param[in] fp - pointer to a stream opened for reading in binary mode
@ returns the 16 bit value as an integer
*/
int fget16le(FILE *fp)
{
int c1, c2;
c1 = fgetc(fp);
c2 = fgetc(fp);
return ((c2 ^ 128) - 128) * 256 + c1;
}
/**
Get a 32-bit little-endian signed integer from a stream.
Does not break, regardless of host integer representation.
@param[in] fp - pointer to a stream opened for reading in binary mode
@ returns the 32 bit value as a long
*/
long fget32le(FILE *fp)
{
int c1, c2, c3, c4;
c1 = fgetc(fp);
c2 = fgetc(fp);
c3 = fgetc(fp);
c4 = fgetc(fp);
return ((c4 ^ 128) - 128) * 256 * 256 * 256 + c3 * 256 * 256 + c2 * 256 + c1;
}