hey everybody,
I'm in an Intro to Programming with C++ class and I need help with an assignment. Is there any way to declare variables or arrays in Hexadecimal? If so, how should I do this? If this isn't possible, is there any way for me to indicate to the compiler that all variables are in Hex? Thanks in advance for your help!

potter

Recommended Answers

All 3 Replies

you mean like this: int x = 0x0F; "0x" says the following characters are hexidecimal

>>is there any way for me to indicate to the compiler that all variables are in Hex
Its not necessaary. All integers can be interpreted as decimal, hecidecimal, or octal. The internal representation is the same for all three types, its only how you want to display the value that changes. For example, to display an integer X as hexidecimal, cout << hex << x;

Essentially what I need to do is have the user input two char arrays that each represent one number in hexadecimal. Then I have to add the two hexadecimal numbers together into a third array containing the sum of the first two in hexadecimal....any thoughts or suggestions?

Here is one way to convert the string to an integer

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
    string input;
    cout << "Enter a hex value ...";
    cin >> input;
    cout << "\n";
    stringstream s;
    s << hex << input;
    int x;
    s >> x;
    cout << "x = " << x << "\n";
    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.