-
Notifications
You must be signed in to change notification settings - Fork 0
/
graycodermaindialog.cpp
82 lines (72 loc) · 1.64 KB
/
graycodermaindialog.cpp
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
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weffc++"
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#include "graycodermaindialog.h"
#include <cassert>
#include <cmath>
#include <iostream>
#include <stdexcept>
#pragma GCC diagnostic pop
ribi::grco::main_dialog::main_dialog(const int normal_int) noexcept
: m_i(normal_int)
{
}
int ribi::grco::main_dialog::BitStringToInt(const std::string& s)
{
int power = 1;
int result = 0;
const auto j = s.rend();
for (auto i = s.rbegin(); i!=j; ++i)
{
const char c = *i;
if (c == '0')
{
//OK
}
else if (c == '1')
{
result += power;
}
else
{
throw std::logic_error("A bitstring must consist of zeroes and ones only");
}
power *= 2;
}
return result;
}
int ribi::grco::main_dialog::GrayToInt(int i)
{
int power = 1;
while (1)
{
const int j = i >> power;
i ^= j;
if (j == 0 || power == 16) return i;
power <<= 1;
}
}
std::string ribi::grco::main_dialog::IntToBitString(int i)
{
assert( i >= 0 && "Did not bother to supply this yet");
std::string s =(i%2 ? "1" : "0" );
i>>=1;
while (i > 0)
{
s = (i%2 ? "1" : "0") + s;
i>>=1;
}
return s;
}
int ribi::grco::main_dialog::IntToGray(const int i)
{
assert( i >= 0 && "Did not bother to supply this yet");
return (i ^ (i>>1));
}
std::ostream& ribi::grco::operator<<(std::ostream& os, const main_dialog& dialog)
{
os
<< "Normal value : " << dialog.GetNormalInt() << " (" << dialog.GetNormalIntAsBitStr() << ")\n"
<< "Gray code value: " << dialog.GetGrayInt() << " (" << dialog.GetGrayIntAsBitStr() << ")\n";
return os;
}