summaryrefslogtreecommitdiffstats
path: root/lib/bitops.c
blob: 5e96e263f3e992f4e59f16a7b8df9f1df4061466 (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
112
113
114
115
/* bitops.c -- Bit-vector manipulation for mkid
   Copyright (C) 1986, 1995, 1996 Free Software Foundation, Inc.
  
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.
  
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
  
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */

#include <config.h>
#include "bitops.h"

static int str_to_int __P((char *bufp, int size));
static char *int_to_str __P((int i, int size));

int
vec_to_bits (char *bit_array, char *vec, int size)
{
  int i;
  int count;

  for (count = 0; (*vec & 0xff) != 0xff; count++)
    {
      i = str_to_int (vec, size);
      BITSET (bit_array, i);
      vec += size;
    }
  return count;
}

int
bits_to_vec (char *vec, char *bit_array, int bit_count, int size)
{
  char *element;
  int i;
  int count;

  for (count = i = 0; i < bit_count; i++)
    {
      if (!BITTST (bit_array, i))
	continue;
      element = int_to_str (i, size);
      switch (size)
	{
	case 4:
	  *vec++ = *element++;
	case 3:
	  *vec++ = *element++;
	case 2:
	  *vec++ = *element++;
	case 1:
	  *vec++ = *element++;
	}
      count++;
    }
  *vec++ = 0xff;

  return count;
}

/* NEEDSWORK: ENDIAN */

static char *
int_to_str (int i, int size)
{
  static char buf0[4];
  char *bufp = &buf0[size];

  switch (size)
    {
    case 4:
      *--bufp = (i & 0xff);
      i >>= 8;
    case 3:
      *--bufp = (i & 0xff);
      i >>= 8;
    case 2:
      *--bufp = (i & 0xff);
      i >>= 8;
    case 1:
      *--bufp = (i & 0xff);
    }
  return buf0;
}

static int
str_to_int (char *bufp, int size)
{
  int i = 0;

  bufp--;
  switch (size)
    {
    case 4:
      i |= (*++bufp & 0xff);
      i <<= 8;
    case 3:
      i |= (*++bufp & 0xff);
      i <<= 8;
    case 2:
      i |= (*++bufp & 0xff);
      i <<= 8;
    case 1:
      i |= (*++bufp & 0xff);
    }
  return i;
}