HEX Addition

mvmalderen 0 Tallied Votes 1K Views Share

I've written a program to add two hexadecimal numbers ...

Njoy !

tux4life

/**********************************
* Written by Mathias Van Malderen
**********************************/

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

string dec2hex(long a);
long hex2dec(const string & hexstr);
string hexadd(const string & hex1, const string & hex2);

int main()
{
	string hex1, hex2;
	cout << endl << "Type two hex numbers: " << endl << endl;
	cout << "> First hex number: _______________\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b";
	cin >> hex1;
	cout << "> First hex number: _______________\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b";
	cin >> hex2;
	cout << endl << endl << "Sum of the two hex numbers: " << hexadd(hex1,hex2) << endl;
	return 0;
}

string hexadd(const string & hex1, const string & hex2)
{
	long n1, n2;
	n1 = hex2dec(hex1);
	n2 = hex2dec(hex2);
	return dec2hex(n1+n2);
}

string dec2hex(long i)
{
	stringstream ss;
	string s;
	hex(ss);
	uppercase(ss);
	ss << i;
	ss >> s;
	return s;
}

long hex2dec(const string & hexstr)
{
	stringstream ss;
	long i = 0;
	hex(ss);
	ss << hexstr;
	ss.clear();
	ss >> i;
	return i;
}
mvmalderen 2,072 Postaholic

If you also need subtraction, multiplication and division for hexadecimal number you only have to change the sign in the return instruction of the hexadd-function from '+' to -, *, /

...

MosaicFuneral 812 Nearly a Posting Virtuoso

You could just shove this in a class and overload the operators to do your operations, and to save time store the value as an integer till a call request the value in its HEX forum.

mvmalderen 2,072 Postaholic

Wow, nice advice ! :)

alebuddy 0 Newbie Poster

Hi, good afternoon!!

Can I get this code in C, NOT in C++. please, I´m a newbie. and I'd like to understand the basic instructions and the logic for this Hex addition. Can you help me, please!! Thanks

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.