home · contact · privacy
Use preprocessor macro instead of constant variable for uchar size.
[plomrogue] / src / readwrite.c
1 #include <stdio.h>
2 #include <limits.h>
3 #include <stdint.h>
4 #define UCHARSIZE (UCHAR_MAX + 1)
5
6 uint16_t read_uint16_bigendian(FILE * file) {
7 // Read uint16 from file in big-endian order.
8   unsigned char a = fgetc(file);
9   unsigned char b = fgetc(file);
10   return (a * UCHARSIZE) + b; }
11
12 void write_uint16_bigendian(uint16_t x, FILE * file) {
13 // Write uint16 to file in beg-endian order.
14   unsigned char a = x / UCHARSIZE;
15   unsigned char b = x % UCHARSIZE;
16   fputc(a, file);
17   fputc(b, file); }
18
19 uint32_t read_uint32_bigendian(FILE * file) {
20 // Read uint32 from file in big-endian order.
21   unsigned char a = fgetc(file);
22   unsigned char b = fgetc(file);
23   unsigned char c = fgetc(file);
24   unsigned char d = fgetc(file);
25   return (a * UCHARSIZE * UCHARSIZE * UCHARSIZE) + (b * UCHARSIZE * UCHARSIZE) + (c * UCHARSIZE) + d; }
26
27 void write_uint32_bigendian(uint32_t x, FILE * file) {
28 // Write uint32 to file in beg-endian order.
29   unsigned char a = x / (UCHARSIZE * UCHARSIZE * UCHARSIZE);
30   unsigned char b = (x - (a * UCHARSIZE * UCHARSIZE * UCHARSIZE)) / (UCHARSIZE * UCHARSIZE);
31   unsigned char c = (x - ((a * UCHARSIZE * UCHARSIZE * UCHARSIZE) + (b * UCHARSIZE * UCHARSIZE))) / UCHARSIZE;
32   unsigned char d = x % UCHARSIZE;
33   fputc(a, file);
34   fputc(b, file);
35   fputc(c, file);
36   fputc(d, file); }