954,483 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

how do you perform hexadecimal addition in C++ with 4 digits?

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

coffeewithcream
Newbie Poster
1 post since Sep 2010
Reputation Points: 10
Solved Threads: 0
 

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

gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387
 

>>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;
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: