comparison th_endian.c @ 0:bd61a80a6c54

Initial import into Mercurial repository. Discarding old cvs/svn history here, because it's cluttered and commit messages are mostly crap.
author Matti Hamalainen <ccr@tnsp.org>
date Wed, 26 Mar 2008 04:41:58 +0200
parents
children 8552edc844a7
comparison
equal deleted inserted replaced
-1:000000000000 0:bd61a80a6c54
1 /*
2 * Endianess handling
3 * Programmed and designed by Matti 'ccr' Hamalainen
4 * (C) Copyright 2002-2007 Tecnic Software productions (TNSP)
5 *
6 * Please read file 'COPYING' for information on license and distribution.
7 */
8 #include "th_endian.h"
9 #include <stdio.h>
10
11
12 /*
13 * Endianess conversion routines
14 */
15 #ifdef TH_BIGENDIAN
16 /* Convert to from Small Endian
17 */
18 void TH_NE16(uint16_t * iVal)
19 {
20 uint16_t r = *iVal;
21 *iVal = ((r & 0xff) << 8) | ((r >> 8) & 0xff);
22 }
23
24
25 void TH_NE32(uint32_t * iVal)
26 {
27 uint32_t r = *iVal;
28 *iVal = ((r & 0xff) << 8) | ((r >> 8) & 0xff) |
29 ((r & 0x00ff0000L) << 8) | ((r >> 8) & 0x00ff0000L);
30 }
31
32
33 /* Convert to Small/Little Endian
34 */
35 uint16_t TH_LE16(uint16_t iVal)
36 {
37 return ((iVal & 0xff) << 8) | ((iVal >> 8) & 0xff);
38 }
39
40
41 uint32_t TH_LE32(uint32_t iVal)
42 {
43 return ((iVal & 0xff) << 8) | ((iVal >> 8) & 0xff) |
44 ((iVal & 0x00ff0000L) << 8) | ((iVal >> 8) & 0x00ff0000L);
45 }
46 #endif /* TH_BIGENDIAN */
47
48
49 /*
50 * File routines for endian-dependant data
51 */
52 #define TH_FILE FILE
53 #define TH_FREAD fread
54 #define TH_FGETC fgetc
55 #define TH_RNAME(X) TH_READ_##X
56 #define TH_CODE_ENDIAN2
57 #include "th_endian2.h"
58 #undef TH_CODE_ENDIAN2
59
60
61 BOOL TH_WRITE_STR(FILE * f, uint8_t * s, size_t l)
62 {
63 return (fwrite(s, sizeof(uint8_t), l, f) == l);
64 }
65
66
67 void TH_WRITE_BE16(FILE * f, uint16_t v)
68 {
69 fputc((v >> 8) & 0xFF, f);
70 fputc(v & 0xFF, f);
71 }
72
73
74 void TH_WRITE_BE32(FILE * f, uint32_t v)
75 {
76 fputc((v >> 24) & 0xFF, f);
77 fputc((v >> 16) & 0xFF, f);
78 fputc((v >> 8) & 0xFF, f);
79 fputc(v & 0xFF, f);
80 }
81
82
83 void TH_WRITE_LE16(FILE * f, uint16_t v)
84 {
85 fputc(v & 0xFF, f);
86 fputc((v >> 8) & 0xFF, f);
87 }
88
89
90 void TH_WRITE_LE32(FILE * f, uint32_t v)
91 {
92 fputc(v & 0xFF, f);
93 fputc((v >> 8) & 0xFF, f);
94 fputc((v >> 16) & 0xFF, f);
95 fputc((v >> 24) & 0xFF, f);
96 }