Imported Upstream version 3.0
[debian/gnuradio] / gr-trellis / src / lib / base.cc
1 /* -*- c++ -*- */
2 /*
3  * Copyright 2002 Free Software Foundation, Inc.
4  *
5  * This file is part of GNU Radio
6  *
7  * GNU Radio is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2, or (at your option)
10  * any later version.
11  *
12  * GNU Radio is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with GNU Radio; see the file COPYING.  If not, write to
19  * the Free Software Foundation, Inc., 51 Franklin Street,
20  * Boston, MA 02110-1301, USA.
21  */
22
23 #include <cstdio>
24 #include <stdexcept>
25 #include <cmath>
26 #include "base.h"
27
28
29 bool dec2base(unsigned int num, int base, std::vector<int> &s)
30 {
31   int l = s.size();
32   unsigned int n=num;
33   for(int i=0;i<l;i++) {
34     s[l-i-1] = n % base; //MSB first
35     n /= base;
36   }
37   if(n!=0) {
38     printf("Number %d requires more than %d digits.",num,l);
39     return false;
40   }
41   else
42     return true;
43 }
44
45
46 unsigned int base2dec(const std::vector<int> &s, int base)
47 {
48   int l = s.size();
49   unsigned int num=0;
50   for(int i=0;i<l;i++)
51       num=num*base+s[i];
52   return num;
53 }
54
55
56 bool dec2bases(unsigned int num, const std::vector<int> &bases, std::vector<int> &s)
57 {
58   int l = s.size();
59   unsigned int n=num;
60   for(int i=0;i<l;i++) {
61       s[l-i-1] = n % bases[l-i-1];
62       n /= bases[l-i-1];
63   }
64   if(n!=0) {
65     printf("Number %d requires more than %d digits.",num,l);
66     return false;
67   }
68   else
69     return true;
70 }
71
72
73
74 unsigned int bases2dec(const std::vector<int> &s, const std::vector<int> &bases)
75 {
76   int l = s.size();
77   unsigned int num=0;
78   for(int i=0;i<l;i++)
79       num = num * bases[i] + s[i];
80   return num;
81 }
82
83
84
85
86
87
88
89
90
91
92