tags:

views:

102

answers:

2

How can access the lower half of a 64bit integer using C or C++? I can do it easily in Assembly but I have no clue on how to do it in C/C++

EDIT: What about accessing the upper half?

+8  A: 
long long BigOne = 0x1234567890ABCDEFLL;
long long LowerHalf = BigOne & 0xFFFFFFFFLL;
long long UpperHalf = (BigOne >> 32) & 0xFFFFFFFFLL;

Sorry if the hexadecimal literals require some prefix/suffix, I'm not very familiar with C. Please fix the answer if you know.

Vilx-
IVlad
Okay, I understand it :)
kotarou3
+1 for taking care of sign extension in UpperHalf
George
Note that whether the right shift performs sign extension is implementation defined and thus not portable. It's usually best to avoid shifting signed values, where possible (it is rarely necessary to shift signed values in practice anyway). As for the suffix question: no suffix is necessary; the hexadecimal literal will be represented by an unsigned type if it cannot be represented by the signed type of the same size (if you used decimal literals, you would need a `u` suffix for "unsigned").
James McNellis
Oh, so it's called "sign extension"? I didn't know what it was. :) I just know that sometimes it duplicates the first bit when right-shifting, so this takes care of that.
Vilx-
A: 

I have used all kinds of tricks to do this before. Using unions, long shifts ect..

Nowadays I just use memcopy. It may sound inefficient, but last time I checked the compiler optimized the code quite nice:

int32_t higher32 (unsigned long long arg)
{
  unsigned char * data = (unsigned char *) arg;
  int32_t result;
  memcpy (&result, data+4, sizeof (int32_t));
  return result;
}

int32_t lower32 (unsigned long long arg)
{
  unsigned char * data = (unsigned char *) arg;
  int32_t result;
  memcpy (&result, data+0, sizeof (int32_t));
  return result;
}
Nils Pipenbrinck
Note that the code will differ on little-endian and big-endian machines.
Vilx-
jep. It will differ..
Nils Pipenbrinck
-1 for ugly endian-dependent code when there's a trivial, fast way to do the right thing with arithmetic.
R..