File: my-endian.cc

package info (click to toggle)
ns2 2.35%2Bdfsg-2.1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 78,780 kB
  • ctags: 27,490
  • sloc: cpp: 172,923; tcl: 107,130; perl: 6,391; sh: 6,143; ansic: 5,846; makefile: 816; awk: 525; csh: 355
file content (52 lines) | stat: -rw-r--r-- 1,199 bytes parent folder | download | duplicates (8)
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
#include "my-endian.h"
 
/* rotates 2 bytes */
unsigned short swap2(u_2bytes In) {
	u_2bytes Out;

	((char*)&(Out))[0] = ((char*)&(In))[1];
	((char*)&(Out))[1] = ((char*)&(In))[0];

	return Out;
}

/* rotates 4 bytes */
u_4bytes rotate4(u_4bytes In) {
	u_4bytes Out;

	((u_2bytes*)&Out)[0] = swap2(((u_2bytes*)&In)[1]);
	((u_2bytes*)&Out)[1] = swap2(((u_2bytes*)&In)[0]);

	return Out;
}

/* detects endian-ness
 * Note:   will not work if sizeof(unsigned long)==1
 */
int IsLittleEndian(void) {
	static const unsigned long long_number = 1;
	return *(const unsigned char *)&long_number;
}

/* changes endian-ness */
void ToOtherEndian(TEntry *e) {

	/* unroll this loop if you want to enumerate u_4bytes members of TEntry_v2 */
	u_4bytes *p;
	for (p = &(e -> head.event_duration); p <= &(e -> url); p++)
		*p = rotate4(*p);

	e -> tail.status = swap2(e -> tail.status);
	
	if (sizeof(method_t) == 2)
		e -> tail.method = swap2(e -> tail.method);
	else
	if (sizeof(method_t) == 4)
		e -> tail.method = rotate4(e -> tail.method);

	if (sizeof(protocol_t) == 2)
		e -> tail.protocol = swap2(e -> tail.protocol);
	else
	if (sizeof(protocol_t) == 4)
		e -> tail.protocol = rotate4(e -> tail.protocol);
}