-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseHelper.cpp
More file actions
101 lines (95 loc) · 2.23 KB
/
BaseHelper.cpp
File metadata and controls
101 lines (95 loc) · 2.23 KB
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
//
// Created by Esteban Agüero Pérez on 10/1/18.
//
#include "BaseHelper.h"
/**
* Convierte un binario a decimal
* @param bin
* @return
*/
int BaseHelper::binToDecimal(std::string bin) {
int temp = 0;
int index;
for (int i = bin.length() - 1; i >= 0; i--) {
index = bin.length() - 1 - i;
temp += (bin[i] - 48) * pow(2, index); // desfasa la conversion char -> int
}
return temp;
}
/**
* Convierte un valor decimal a binario
* @param decimal
* @return
*/
std::string BaseHelper::decimalToBin(int decimal) {
std::string temp = "";
std::string val;
if (decimal == 0) {
return "00";
} else if (decimal < 0) {
decimal *= -1;
decimal -= 1;
while (decimal > 0) {
if (decimal % 2) {
val = '0';
} else {
val = '1';
}
val += temp;
temp = val;
decimal /= 2;
}
val = '1';
val += temp;
temp = val;
} else {
while (decimal > 0) {
val = (decimal % 2 + 48);
val += temp;
temp = val;
decimal /= 2;
}
val = '0';
val += temp;
temp = val;
}
return temp;
}
/**
* Conversionde binario a decimal especificando la cantidad de bits
* @param bin
* @param bits
* @return
*/
int BaseHelper::binToDecimal(std::string bin, int bits) {
return binToDecimal(bin); // cambiar esto para verificar si es negativo y en complemento
}
/**
* Convierte de decimal a binario de una cantidad de bits
* @param decimal
* @param bits
* @return
*/
std::string BaseHelper::decimalToBin(int decimal, int bits) {
std::string val, temp;
val = decimalToBin(decimal);
int diferencia = bits - val.length(); //por el bit de signo
if (diferencia <= 0) {
temp = val.substr(val.length() - bits, val.length());
} else {
temp = getExtendN(val[0], diferencia, val);
}
return temp;
}
/**
* Se extiende el dato con caracter dado n veces
* @param caracter
* @param n
* @param dato
* @return
*/
std::string BaseHelper::getExtendN(char caracter, int n, std::string dato) {
std::string temp(n, caracter);
temp += dato;
return temp;
}