Converting HEX to DEC [duplicate] - c++

This question already has answers here:
C++: Converting Hexadecimal to Decimal
(11 answers)
Closed 2 years ago.
I'm trying to use a C++ program to convert a hexadecimal value into a decimal value. Just can't come up with a working code.
This is the best thing I have come up with:
int main () {
string link;
string hex_code;
int dec_code;
int i;
int n = 6;
int num;
int hex;
cout << "Insert 1 of the HEX characters at a time:";
for (i = 0; i < n; i++) {
cin >> hex_code;
}
for (i = 0; i < n; i++) {
if (hex_code == "A") {
hex_code = 10;
}
else if (hex_code == "B") {
hex_code = 11;
}
else if (hex_code == "C") {
hex_code = 12;
}
else if (hex_code == "D") {
hex_code = 13;
}
else if (hex_code == "E") {
hex_code = 14;
}
else if (hex_code == "F") {
hex_code = 15;
}
else {
hex_code = hex_code;
}
num = hex * pow (16, i);
}
for (i = 0; i < n; i++) {
dec_code = dec_code + num;
}
cout << dec_code;
return 0;
}
Any help/feddback/opinions are welcome.
Edit: Thank you for all your help. Found the code I tryed to create, but failed, here: https://stackoverflow.com/a/27334556/13615474

There is a hex manipulator in iomanip library of C++
cout << "Insert 1 of the HEX characters at a time:";
for (i = 0; i < n; i++) {
int hexcode;
std::cin >> std::hex >> hexcode;
std::cout << hexcode << std::endl;
}
This would print decimal equivalent of given hex code

Hex to decimal conversion can be performed by reading the input number as a character array and performing the conversion arithmetic on each character.
Here is a working example for converting hexadecimal into decimal:
// File name: HexToDec.cpp
#include <iostream>
#include <cstring>
using namespace std;
int hexToDec(char hexNumber[]) {
int decimalNumber = 0;
int len = strlen(hexNumber);
for (int base = 1, i=(len-1); i>=0; i--, base *= 16) {
// Get the hex digit in upper case
char digit = toupper(hexNumber[i]);
if ( digit >= '0' && digit <='9' ) {
decimalNumber += (digit - 48)*base;
}
else if ( digit >='A' && digit <='F' ) {
decimalNumber += (digit - 55)*base;
}
}
return decimalNumber;
}
int main() {
char hexNumber[80];
// Read the hexadecimal number as a character array
cout << "Enter hexadecimal number: ";
cin >> hexNumber;
cout << hexNumber << " in decimal format = " << hexToDec(hexNumber) << "\n";
return 0;
}
Output:
Enter hexadecimal number: DEC
DEC in decimal format = 3564
More information:
https://www.geeksforgeeks.org/program-for-hexadecimal-to-decimal/

Here is a simple code fragment using a lookup table:
char c;
static const char hex_to_decimal[] = "0123456789ABCDEF";
std::cin >> c;
int decimal = 0;
for (decimal = 0; decimal < sizeof(hex_to_decimal) - 1; ++decimal)
{
if (hex_to_decimal[i] == c)
{
break;
}
}
Another conversion method:
std::cin >> c;
int decimal;
if (is_digit(c))
{
decimal = c - '0';
}
else
{
decimal = 10 + c - 'A';
}
The above code fragment assumes that the encoding has 'A'...'F' contiguous.
The first example is more portable.

Related

std::stoi only converts first few characters

I am using stoi in one of my functions with the intent of converting a string of numbers into an integer. I was about halfway through a homework problem but then I ran into this. Oddly, if the number has an even number of characters, stoi only converts the first half. Any help would be greatly appreciated!
Code:
#include <fstream>
#include <vector>
#include <string>
using namespace std;
string start;
string endD;
int sDigit;
int eDigit;
int i;
vector<int> palindromes;
void construct(int layer, int digits, string prev)
{
string temp = prev;
if(layer > (digits % 2) + digits/2)
{
short a = (short) digits/2;
for(int i = a; i >= 0; i--)
{
if(i == a && digits % 2 == 1)
{
continue;
}
else
{
temp.push_back(temp[i]);
}
}
cout << temp << " " << stoi(temp) << endl; // Output is here
palindromes.push_back(stoi(temp));
}
else if(layer == 1 && digits == sDigit)
{
for(int i = start[0] - '0'; i < 10; i++)
{
temp[0] = i + '0';
construct(layer + 1, digits, temp);
}
}
else if(layer == 1 && digits == eDigit)
{
for(int i = '1'; i <= endD[0]; i++)
{
temp[0] = i;
construct(layer + 1, digits, temp);
temp = prev;
}
}
else if(layer == 1)
{
for(int i = 1; i < 10; i++)
{
temp[0] = '0' + i;
construct(layer + 1, digits, temp);
temp = prev;
}
}
else
{
for(int i = 0; i < 10; i++)
{
temp.push_back(i + '0');
construct(layer + 1, digits, temp);
temp = prev;
}
}
}
int main()
{
int startD, endDD;
cin >> startD >> endDD;
start = to_string(startD);
endD = to_string(endDD);
int tempS = startD;
int tempE = endDD;
while(tempS != 0)
{
tempS /= 10;
sDigit++;
}
while(tempE != 0)
{
tempE /= 10;
eDigit++;
}
for(int i = sDigit; i <= eDigit; i++)
{
construct(1, i, "x");
}
for(int i = 0; i < palindromes.size(); i++)
{
//cout << palindromes[i] << endl;
}
}```
Input: 1 1000
Output:
Your code has undefined behavior because in this line
temp.push_back(temp[i]);
you are accessing temp out-of-bounds. You can see this by adding a line
std::cout << "check " << i << " " << temp.size() << "\n";
just before that line.
Output will be (see here):
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
check 1 1
check 0 2
1
...
When the size is 1 the last valid index is 0. The problem is not with stoi but with the logic of your algorithm.

Code keeps returning 255 or -1073741819 when type casting char to string

This is a code for converting a string to lowercase letters. I used the idea of the ASCII value difference between uppercase and lower case letters in alphabet being 32. I am using codeblocks. The code does the conversion but gives this error. Why am I getting an error in this case, although there is no error in casting string to char? How do I correct this?
#include<iostream>
using namespace std;
string convertlow (string input )
{
char letters[255];
int ascii[255];
for (int i=0;i<255;i++)
{
letters[i]=input[i];
ascii[i]=(int)letters[i];
if (ascii[i] < 91)
{
ascii[i] = ascii[i] + 32;
letters[i] = (char) ascii[i];
input[i] = letters[i];
}
}
return input;
}
int main()
{
string in;
cin >> in;
cout << "The lowercase version is: \n" << convertlow(in);
return 0;
};
You should change:
if (ascii[i]<91)
{
ascii[i]=ascii[i]+32;
letters[i]= (char)ascii[i];
input[i]=letters[i];
}
to:
if(ascii[i] >= 'A' && asc[i] <= 'Z')
{
ascii[i] = ascii[i]+('a' - 'A');
letters[i] = (char)ascii[i];
input[i] = letters[i];
}
But your problem is array out of range (string size should be less than 255). To solve this you can change your method to:
string convertlow (string input ){
for(int i = 0 ; i < input.size() ; ++i){
if(islower(input[i]) ){
input[i] = tolower(input[i]);
}
}
return input;
}
You need to include headers: string and algorithm

Parenthesized Expression (Infix and Post fix) Conversion and Evaluation

I have the below code working fine but outputs only 2nd input, not 1st or 3rd.
My code should get fully parenthesized expression from console and convert it to postfix expression and then that postfix expression should be evaluated in modulo 10.Therefore, all results (including intermediate results) are single decimal digits in {0, 1, …, 9}. I need to store only single digits in the stack.
My inputs and outputs are shown in below.I only got 2nd input correctly.
Please advise.
Expression 1: (((2+(5^2))+7)
Answer:
252^+7+
4 in modulo 10
Expression 2: ((((2+5)*7)+((9*3)*2))^2)
Answer:
25+7*93*2*+2^
9 in modulo 10
Expression 3: ((((2*3)*(4*6))*7)+(((7+8)+9)*((2+4)*((7+8)+9))))
Answer:
23*46*7*789++24+78+9+**+
4 in modulo 10
My code:
#include <iostream>
#include <string>
#include<sstream>
using namespace std;
class STACK {
private:
char *s;
int N;
public:
STACK(int maxN) {
s = new char[maxN];
N = 0;
}
int empty() const {
return N == 0;
}
void push(char item) {
s[N++] = item;
}
char pop() {
return s[--N];
}
};
int main() {
string infixExpr;
string postfixExpr = "";
cout << "Enter infix expression:" << endl;
cin >> infixExpr; //converting to postfix read from the input
int N = infixExpr.size(); //strncpy(a, infixExpr.c_str(), N);
STACK ops(N);
char ch;
for (int i = 0; i < N; i++) {
if (infixExpr[i] == ')')
{
ch = ops.pop();
postfixExpr.push_back(ch);
}
if ((infixExpr[i] == '+') || (infixExpr[i] == '*') || (infixExpr[i] == '^'))
ops.push(infixExpr[i]);
if ((infixExpr[i] >= '0') && (infixExpr[i] <= '9'))
{
//cout << infixExpr[i] << " ";
postfixExpr.push_back(infixExpr[i]);
}
}
cout <<"Answer :"<<endl;
cout <<postfixExpr <<endl; //evaluate post fix expression
N = postfixExpr.size();
STACK save(N);
int result;
int num;
int count = 0;
string temp = "";
for (int i = 0; i < N; i++) {
// cout << " Expr[i] " << postfixExpr[i] << endl;
if (postfixExpr[i] == '+')
save.push((save.pop() + save.pop()) % 10);
if (postfixExpr[i] == '*')
save.push((save.pop() * save.pop()) % 10);
if (postfixExpr[i] == '^') {
count = save.pop() - '0';
num = save.pop() - '0'; //cout << result << "- " <<"-" <<count<<endl;
result = 1;
for(int j = 1; j <= count; j++)
{
result = result * num;
result = result % 10;
}
stringstream convert;
convert << result;//add the value of Number to the characters in the stream
temp = convert.str();//set Result to the content of the stream
save.push(temp[0]);
}
if ((postfixExpr[i] >= '0') && (postfixExpr[i] <= '9'))
{
save.push(postfixExpr[i]);
}
}
cout << save.pop() <<" in module 10"<< endl;
return 1;
}

C++ binary input as a string to a decimal

I am trying to write a code that takes a binary number input as a string and will only accept 1's or 0's if not there should be an error message displayed. Then it should go through a loop digit by digit to convert the binary number as a string to decimal. I cant seem to get it right I have the fact that it will only accept 1's or 0's correct. But then when it gets into the calculations something messes up and I cant seem to get it correct. Currently this is the closest I believe I have to getting it working. could anyone give me a hint or help me with what i am doing wrong?
#include <iostream>
#include <string>
using namespace std;
string a;
int input();
int main()
{
input();
int decimal, x= 0, length, total = 0;
length = a.length();
// atempting to make it put the digits through a formula backwords.
for (int i = length; i >= 0; i--)
{
// Trying to make it only add the 2^x if the number is 1
if (a[i] = '1')
{
//should make total equal to the old total plus 2^x if a[i] = 1
total = total + pow(x,2);
}
//trying to let the power start at 0 and go up each run of the loop
x++;
}
cout << endl << total;
int stop;
cin >> stop;
return 0;
}
int input()
{
int x, x2, count, repeat = 0;
while (repeat == 0)
{
cout << "Enter a string representing a binary number => ";
cin >> a;
count = a.length();
for (x = 0; x < count; x++)
{
if (a[x] != '0' && a[x] != '1')
{
cout << a << " is not a string representing a binary number>" << endl;
repeat = 0;
break;
}
else
repeat = 1;
}
}
return 0;
}
I don't think that pow suits for integer calculation. In this case, you can use shift operator.
a[i] = '1' sets the value of a[i] to '1' and return '1', which is always true.
You shouldn't access a[length], which should be meaningless.
fixed code:
int main()
{
input();
int decimal, x= 0, length, total = 0;
length = a.length();
// atempting to make it put the digits through a formula backwords.
for (int i = length - 1; i >= 0; i--)
{
// Trying to make it only add the 2^x if the number is 1
if (a[i] == '1')
{
//should make total equal to the old total plus 2^x if a[i] = 1
total = total + (1 << x);
}
//trying to let the power start at 0 and go up each run of the loop
x++;
}
cout << endl << total;
int stop;
cin >> stop;
return 0;
}
I would use this approach...
#include <iostream>
using namespace std;
int main()
{
string str{ "10110011" }; // max length can be sizeof(int) X 8
int dec = 0, mask = 1;
for (int i = str.length() - 1; i >= 0; i--) {
if (str[i] == '1') {
dec |= mask;
}
mask <<= 1;
}
cout << "Decimal number is: " << dec;
// system("pause");
return 0;
}
Works for binary strings up to 32 bits. Swap out integer for long to get 64 bits.
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
string getBinaryString(int value, unsigned int length, bool reverse) {
string output = string(length, '0');
if (!reverse) {
for (unsigned int i = 0; i < length; i++) {
if ((value & (1 << i)) != 0) {
output[i] = '1';
}
}
}
else {
for (unsigned int i = 0; i < length; i++) {
if ((value & (1 << (length - i - 1))) != 0) {
output[i] = '1';
}
}
}
return output;
}
unsigned long getInteger(const string& input, size_t lsbindex, size_t msbindex) {
unsigned long val = 0;
unsigned int offset = 0;
if (lsbindex > msbindex) {
size_t length = lsbindex - msbindex;
for (size_t i = msbindex; i <= lsbindex; i++, offset++) {
if (input[i] == '1') {
val |= (1 << (length - offset));
}
}
}
else { //lsbindex < msbindex
for (size_t i = lsbindex; i <= msbindex; i++, offset++) {
if (input[i] == '1') {
val |= (1 << offset);
}
}
}
return val;
}
int main() {
int value = 23;
cout << value << ": " << getBinaryString(value, 5, false) << endl;
string str = "01011";
cout << str << ": " << getInteger(str, 1, 3) << endl;
}
I see multiple misstages in your code.
Your for-loop should start at i = length - 1 instead of i = length.
a[i] = '1' sets a[i] to '1' and does not compare it.
pow(x,2) means and not . pow is also not designed for integer operations. Use 2*2*... or 1<<e instead.
Also there are shorter ways to achieve it. Here is a example how I would do it:
std::size_t fromBinaryString(const std::string &str)
{
std::size_t result = 0;
for (std::size_t i = 0; i < str.size(); ++i)
{
// '0' - '0' == 0 and '1' - '0' == 1.
// If you don't want to assume that, you can use if or switch
result = (result << 1) + str[i] - '0';
}
return result;
}

C++: Change of base function (i.e. hex to octal, decimal, etc.) - Output slightly off for hex values

I need to create a generic function that changes from any starting base, to any final base. I have everything down, except my original function took (and takes) an int value for the number that it converts to another base. I decided to just overload the function. I am Ok with changing between every base, but am slightly off when using my new function to take in a string hex value.
The code below should output 1235 for both functions. It does for the first one, but for the second, I am currently getting 1347. Decimal to Hex works fine - It's just the overloaded function (Hex to anything else) that is slightly off.
Thanks.
#include <iostream>
#include <stack>
#include <string>
#include <cmath>
using namespace std;
void switchBasesFunction(stack<int> & myStack, int startBase, int finalBase, int num);
void switchBasesFunction(stack<int> & myStack, int startBase, int finalBase, string s);
int main()
{
stack<int> myStack;
string hexNum = "4D3";
switchBasesFunction(myStack, 8, 10, 2323);
cout << endl << endl;
switchBasesFunction(myStack, 16, 10, hexNum);
return 0;
}
void switchBasesFunction(stack<int> & myStack, int startBase, int finalBase, int num)
{
int totalVal = 0;
string s = to_string(num);
for (int i = 0; i < s.length(); i++)
{
myStack.push(s.at(i) - '0');
}
int k = 0;
while (myStack.size() > 0)
{
totalVal += (myStack.top() * pow(startBase, k++));
myStack.pop();
}
string s1;
while (totalVal > 0)
{
int temp = totalVal % finalBase;
totalVal = totalVal / finalBase;
char c;
if (temp < 10)
{
c = temp + '0';
s1 += c;
}
else
{
c = temp - 10 + 'A';
s1 += c;
}
}
for (int i = s1.length() - 1; i >= 0; i--)
{
cout << s1[i];
}
cout << endl << endl;
}
void switchBasesFunction(stack<int> & myStack, int startBase, int finalBase, string s)
{
int totalVal = 0;
for (int i = 0; i < s.length(); i++)
{
myStack.push(s.at(i) - '0');
}
int k = 0;
while (myStack.size() > 0)
{
totalVal += (myStack.top() * pow(startBase, k++));
myStack.pop();
}
string s1;
while (totalVal > 0)
{
int temp = totalVal % finalBase;
totalVal = totalVal / finalBase;
char c;
if (temp < 10)
{
c = temp + '0';
s1 += c;
}
else
{
c = temp - 10 + 'A';
s1 += c;
}
}
for (int i = s1.length() - 1; i >= 0; i--)
{
cout << s1[i];
}
cout << endl << endl;
}
Sorry, but I'm having issues understanding your code, so I thought I'd simplify it.
Here's the algorithm / code (untested):
void convert_to_base(const std::string& original_value,
unsigned int original_base,
std::string& final_value_str,
unsigned int final_base)
{
static const std::string digit_str =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if ((original_base > digit_str.length()) || (final_base > digit_str.length())
{
std::cerr << "Base value exceeds limit of " << digit_str.length() << ".\n";
return;
}
// Parse string from right to left, smallest value to largest.
// Convert to decimal.
unsigned int original_number = 0;
unsigned int digit_value = 0;
int index = 0;
for (index = original_value.length(); index > 0; --index)
{
std::string::size_type posn = digit_str.find(original_value[index];
if (posn == std::string::npos)
{
cerr << "unsupported digit encountered: " << original_value[index] << ".\n";
return;
}
digit_value = posn;
original_number = original_number * original_base + digit_value;
}
// Convert to a string of digits in the final base.
while (original_number != 0)
{
digit_value = original_number % final_base;
final_value_str.insert(0, 1, digit_str[digit_value]);
original_number = original_number / final_base;
}
}
*Warning: code not tested via compiler.**