0

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

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by firstPerson
0

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

Edited by gerard4143: n/a

1

>>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){
   ++addedValue;
   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;

Edited by firstPerson: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.