Home > Software engineering >  How to combine two numbers to get a long long integer?
How to combine two numbers to get a long long integer?

Time:02-03

I am trying to combine two large numbers together which would result making a "long long int". For example:

a = -1716642972;
b = 43828807;
z = a and b;

In this case, I want z to equal -171664297243828807.

I know most of you are thinking, "why on earth would you want to do that?". You'll just have to trust me when I say there is a reason for wanting to do this.

details to know:

  • Variable a is expected to be 10 digits so I will be defining it as a "long" integer. Just to be on the safe side. It can be either a negative or a positive number.
  • variable b will be the last 8 digits of the seconds value from the time function. This means there is a chance for variable b to equal, 00000000. The number will always be positive.
  • variable z will be a combination of variables a and b. It has to be a "long long int". Variable a will always be before variable b. If variable b equals 00000000, then I want that implemented in variable z: -171664297200000000 or -171664297200000001, etc...

I have tried setting "long long z" equal to (a*100000000) b but I end up getting some crazy number. This also gives the warning of an overflow. I'm assuming this has to do with integer types. Any help will be appreciated. Thanks!

CodePudding user response:

What I ended up doing is using the following code:

long a = -1716642972;
int b = 43828807;

// combine a and b as a string. Be sure to specify variable types.
char string[20];
snprintf(string, 20, "%ld%i", a, b);

//convert the string into a long long (%lld)
long long z;
sscanf(concat, "%lld", &z);

While this may be a lengthier process, it got the job done. On the plus side, with this process I don't need to be picky with integer types, as long as I specify what those types are.

CodePudding user response:

Simply doing (a*100000000) b can overflow if a is not large enough to hold the resulting type. A long long is guaranteed to hold a signed 64-bit quantity, so cast a to that type before performing the calculation.

Also, if a is negative, then you'll first want to invert the sign of b before adding it.

long long z = (long long)a * 100000000   (a>=0 ? b : -b);
  •  Tags:  
  • Related