C++ - unsigned long long int comparison

May 5, 2010 at 2:32pm
Hey all,

I have two unsigned long long int variables that i want to compare (such as >=, == etc) and occasionally want to apply arithmatic to (simple - operations mainly).

For example if i have two unsigned long long int variables:
a = 3316757944182080000
b = 1284800371338750000

and i want to subtract b from a (such as: c = a -b) i end up getting rubbish data in c:

that is c prints as (1.64148E+19) where c should actually equal (2.03196E+18).

any ideas?

thanks.
May 5, 2010 at 3:31pm
D:\prog\cc\foo> copy con a.cpp
#include <iostream>
using namespace std;

int main()
  {
  typedef unsigned long long int huge;

  huge a = 3316757944182080000ULL;
  huge b = 1284800371338750000ULL;

  huge c = a - b;

  cout << c << endl;

  return 0;
  }

^Z
        1 file(s) copied.

D:\prog\cc\foo> g++ a.cpp

D:\prog\cc\foo> a
2031957572843330000

D:\prog\cc\foo> _

Turn on all your compiler warnings and tell us what you get (and what compiler you are using).
May 5, 2010 at 3:40pm
Im using g++ and i get no warnings.
Your code is correct however i have a random seed seting a var variable - such as -
1
2
3
4
5
6
7
8
               for(int j =0; j < 8 ; j++)
	{
		for(int i =0; i < 8 ; i++)
			val= (val << 8)+(rand()+i);

		unused.push_back(val);
		cout<<val<<endl;
	}


during which at a later time i wish to set an unsigned long long int variable (c) to equal the difference between two instances of var - such as -

1
2
               c = var[1] - var[2];
               cout<<c<<endl;


this is where my program prints the wrong calculation.
any ideas?
May 5, 2010 at 4:09pm
I think you get wrong results when var[2] is larger than var[1], eg:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main()
{

unsigned long long a=100000000, b=100000001;

unsigned long long result_unsigned=a-b;
long long result_signed=a-b;

cout <<"unsigned a-b== "<<result_unsigned<<endl;
cout <<"signed    a-b== "<<result_signed<<endl;

}


Topic archived. No new replies allowed.