How do you perform hexadecimal addition in C++?

like

ACD2 + 23E1 = D0D3

5A72 + 4573 = 9FE5

___________________________________________________

the addends will be asked by the program then the program should show the sum

___________________________________________________

the addends required are only 2

## All 2 Replies

The only thing you have to worry about is displaying the values...Try something like below
std::cout<<std::hex<<1234<<std::endl;

When you input the values make sure you use this format 0xXXX again see below

0x4d2

>>5A72 + 4573 = 9FE5

In an algorithmic way, you can do something like this :

``````string hex1 = "5A72";
string hex2 = "4573"
string res;
assert(hex1.size() == hex2.size());
bool hasCarry = false;
for(size_t n = 0; n < hex1.size(); ++n){
string hexValues = "0123456789ABCDEF";
char addedValue = (hex1[n] + hex2[n]);
if(hasCarry){
hasCarry = false;
}
if(addedValue > 16) {
hasCarry = true;
addedValue %= 16; //map 0-15
}
res.push_back(  hexValues[ addedValue ] )
}``````

The basic idea is to use simple addition algorithm like you would do on paper.
THe above code is not compiled so no guarantee. But it should give you and idea.

But an easy way would be something like so :

``````int hex1 = 0x5A72;
int hex2 = 0x4573;
int res = hex1 + hex2;
std::cout << std::hex << res << endl;``````
Be a part of the DaniWeb community

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