4

I want to store two 32-bit values in a single long int variable.

How would you do this on a 32-bit OS using C? Is it possible to store the data in a single long long variable? If so, how is that done?

phuclv
  • 37,963
  • 15
  • 156
  • 475
Syedsma
  • 1,183
  • 5
  • 17
  • 22
  • 4
    why would not you use a structure of two 32-bit integers ? – SirDarius Aug 11 '11 at 14:19
  • 1
    Why would you want to do this? – Matthijs Bierman Aug 11 '11 at 14:22
  • code is already present, so I just want to know 64bit data can be store in one single long int variable or not – Syedsma Aug 11 '11 at 14:22
  • @Syedsma: In addition to the given answers it may interest you, that on Windows the [MAKELPARAM](http://msdn.microsoft.com/en-us/library/ms632661\(v=vs.85\).aspx) macro does this (except it combines 2x16-bit into one 32-bit word). [LOWORD](http://msdn.microsoft.com/en-us/library/ms632659\(v=vs.85\).aspx), [HIWORD](http://msdn.microsoft.com/en-us/library/ms632657\(v=vs.85\).aspx) can then later be used to extract the high and low words. – user786653 Aug 11 '11 at 14:27

3 Answers3

10

Use an uint64_t and bitwise operators.

uint64_t i64;
uint32_t a32, b32;

// Be carefull when shifting the a32.
// It must be converted to a 64 bit value or you will loose the bits
// during the shift. 
i64 = ((uint64_t)a32 << 32) | b32;
cnicutar
  • 178,505
  • 25
  • 365
  • 392
0

Assuming a long is 64 bits on your platform,

int v1 = 123;
int v2 = 456;
long val = v1 << 32 | v2;
Kevin
  • 24,871
  • 19
  • 102
  • 158
0

Unless sizeof(long int) == 8, the answer is no. If that equality is true, then use Kevin's or cnicutar's answer.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • 1
    Not quite correct. The standard allows `INT_MIN` to be -32767 and `INT_MAX` to be 32767. So what is really required is for the type used to store the result to be twice the size of the operands (original values) at least. – jweyrich Aug 11 '11 at 14:35
  • @jweyrich: I understand the standard allows an int to be 16 bits in size. However, he asked if he could fit two 32bit numbers into a long int. If a long int is 4 bytes long, that would be quite difficult. Also, a long int simply must be greater or equal to the size of an int. – Bill Lynch Aug 11 '11 at 16:10
  • My point is that your answer is assuming that `int` is 32 bits, which might not be the case. – jweyrich Aug 11 '11 at 16:41