summaryrefslogtreecommitdiff
path: root/im/src/im_bin.cpp
blob: de279b528e5dd54010e20578694d352dba63d4f9 (plain)
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/** \file
 * \brief Binary Data Utilities
 *
 * See Copyright Notice in im_lib.h
 * $Id: im_bin.cpp,v 1.1 2008/10/17 06:10:16 scuri Exp $
 */

#include <assert.h>

#include "im_util.h"


int imBinCPUByteOrder(void)
{
  static int CPUByteOrder = -1;

  if (CPUByteOrder == -1)
  {
	  unsigned short w = 0x0001;
	  unsigned char* b = (unsigned char*)&w;
	  CPUByteOrder = (b[0] == 0x01)? IM_LITTLEENDIAN: IM_BIGENDIAN;
  }

  return CPUByteOrder;
}

void imBinSwapBytes(void *data, int count, int size)
{
  switch(size)
  {
  case 2:
    imBinSwapBytes2(data, count);
    break;
  case 4:
    imBinSwapBytes4(data, count);
    break;
  case 8:
    imBinSwapBytes8(data, count);
    break;
  }
}

void imBinSwapBytes2(void *data, int count)
{
	assert(data);

	unsigned char lTemp;
  unsigned char *values = (unsigned char *)data;

	while (count-- != 0)
	{
		lTemp = values[1];
		values[1] = values[0];
		values[0] = lTemp;

		values += 2;
	}
}

void imBinSwapBytes4(void *data, int count)
{
	assert(data);

	unsigned char lTemp;
  unsigned char *values = (unsigned char *)data;

	while (count-- != 0)
	{
		lTemp = values[3];
		values[3] = values[0];
		values[0] = lTemp;

		lTemp = values[2];
		values[2] = values[1];
		values[1] = lTemp;

		values += 4;
	}
}

void imBinSwapBytes8(void *data, int count)
{
  assert(data);

	unsigned char lTemp;
  unsigned char *values = (unsigned char *)data;
	
	assert(values);

	while (count-- != 0)
	{
		lTemp = values[7];
		values[7] = values[0];
		values[0] = lTemp;

		lTemp = values[6];
		values[6] = values[1];
		values[1] = lTemp;

		lTemp = values[5];
		values[5] = values[2];
		values[2] = lTemp;

		lTemp = values[4];
		values[4] = values[3];
		values[3] = lTemp;

		values += 8;
	}
}