home · contact · privacy
Restructured source tree. Code moves to src/, object files to build/.
[plomrogue] / src / readwrite.c
1 #include <stdio.h>
2 #include <limits.h>
3 #include <stdint.h>
4
5 uint16_t read_uint16_bigendian(FILE * file) {
6 // Read uint16 from file in big-endian order.
7   const uint16_t nchar = UCHAR_MAX + 1;
8   unsigned char a = fgetc(file);
9   unsigned char b = fgetc(file);
10   return (a * nchar) + b; }
11
12 void write_uint16_bigendian(uint16_t x, FILE * file) {
13 // Write uint16 to file in beg-endian order.
14   const uint16_t nchar = UCHAR_MAX + 1;
15   unsigned char a = x / nchar;
16   unsigned char b = x % nchar;
17   fputc(a, file);
18   fputc(b, file); }
19
20 uint32_t read_uint32_bigendian(FILE * file) {
21 // Read uint32 from file in big-endian order.
22   const uint16_t nchar = UCHAR_MAX + 1;
23   unsigned char a = fgetc(file);
24   unsigned char b = fgetc(file);
25   unsigned char c = fgetc(file);
26   unsigned char d = fgetc(file);
27   return (a * nchar * nchar * nchar) + (b * nchar * nchar) + (c * nchar) + d; }
28
29 void write_uint32_bigendian(uint32_t x, FILE * file) {
30 // Write uint32 to file in beg-endian order.
31   const uint16_t nchar = UCHAR_MAX + 1;
32   unsigned char a = x / (nchar * nchar * nchar);
33   unsigned char b = (x - (a * nchar * nchar * nchar)) / (nchar * nchar);
34   unsigned char c = (x - ((a * nchar * nchar * nchar) + (b * nchar * nchar))) / nchar;
35   unsigned char d = x % nchar;
36   fputc(a, file);
37   fputc(b, file);
38   fputc(c, file);
39   fputc(d, file); }
40