1 /* CpuArch.h
2 2009-03-22 : Igor Pavlov : Public domain */
3 
4 #ifndef __CPU_ARCH_H
5 #define __CPU_ARCH_H
6 
7 #ifdef __cplusplus
8 extern "C" {
9 #endif
10 
11 /*
12 LITTLE_ENDIAN_UNALIGN means:
13   1) CPU is LITTLE_ENDIAN
14   2) it's allowed to make unaligned memory accesses
15 if LITTLE_ENDIAN_UNALIGN is not defined, it means that we don't know
16 about these properties of platform.
17 */
18 
19 #if defined(_M_IX86) || defined(_M_X64) || defined(_M_AMD64) || defined(__i386__) || defined(__x86_64__)
20 #define LITTLE_ENDIAN_UNALIGN
21 #endif
22 
23 #ifdef LITTLE_ENDIAN_UNALIGN
24 
25 #define GetUi16(p) (*(const UInt16 *)(p))
26 #define GetUi32(p) (*(const UInt32 *)(p))
27 #define GetUi64(p) (*(const UInt64 *)(p))
28 #define SetUi16(p, d) *(UInt16 *)(p) = (d);
29 #define SetUi32(p, d) *(UInt32 *)(p) = (d);
30 
31 #else
32 
33 #define GetUi16(p) (((const Byte *)(p))[0] | ((UInt16)((const Byte *)(p))[1] << 8))
34 
35 #define GetUi32(p) ( \
36              ((const Byte *)(p))[0]        | \
37     ((UInt32)((const Byte *)(p))[1] <<  8) | \
38     ((UInt32)((const Byte *)(p))[2] << 16) | \
39     ((UInt32)((const Byte *)(p))[3] << 24))
40 
41 #define GetUi64(p) (GetUi32(p) | ((UInt64)GetUi32(((const Byte *)(p)) + 4) << 32))
42 
43 #define SetUi16(p, d) { UInt32 _x_ = (d); \
44     ((Byte *)(p))[0] = (Byte)_x_; \
45     ((Byte *)(p))[1] = (Byte)(_x_ >> 8); }
46 
47 #define SetUi32(p, d) { UInt32 _x_ = (d); \
48     ((Byte *)(p))[0] = (Byte)_x_; \
49     ((Byte *)(p))[1] = (Byte)(_x_ >> 8); \
50     ((Byte *)(p))[2] = (Byte)(_x_ >> 16); \
51     ((Byte *)(p))[3] = (Byte)(_x_ >> 24); }
52 
53 #endif
54 
55 #if defined(LITTLE_ENDIAN_UNALIGN) && defined(_WIN64) && (_MSC_VER >= 1300)
56 
57 #pragma intrinsic(_byteswap_ulong)
58 #pragma intrinsic(_byteswap_uint64)
59 #define GetBe32(p) _byteswap_ulong(*(const UInt32 *)(const Byte *)(p))
60 #define GetBe64(p) _byteswap_uint64(*(const UInt64 *)(const Byte *)(p))
61 
62 #else
63 
64 #define GetBe32(p) ( \
65     ((UInt32)((const Byte *)(p))[0] << 24) | \
66     ((UInt32)((const Byte *)(p))[1] << 16) | \
67     ((UInt32)((const Byte *)(p))[2] <<  8) | \
68              ((const Byte *)(p))[3] )
69 
70 #define GetBe64(p) (((UInt64)GetBe32(p) << 32) | GetBe32(((const Byte *)(p)) + 4))
71 
72 #endif
73 
74 #define GetBe16(p) (((UInt16)((const Byte *)(p))[0] << 8) | ((const Byte *)(p))[1])
75 
76 #ifdef __cplusplus
77 }
78 #endif
79 
80 #endif
81