1
votes

I have (not mine) a program that reads long values from a data-file.
I can change the numbers in the data-file and I can do s.th. with the number the program has read from the data-file.

Now I want to write 2 integer-values (2*4 byte) in the data-file instead of one (small) long-value (8 byte).

What do I have to do with the number I get in the program to 'split' that into the two initial integer-values?

What I read is s.th. like 54257654438765. How do I split that?
That program offers me some (c-like) bitwise operations:

   x = x << y;         // left shift
   x = x >> y;         // right shift
   b = ((x & y) != 0); // Bitwise AND
   b = ((x | y) != 0); // Bitwise OR
   b = x ^ y;          // Bitwise Exclusive Operation OR

But these operators are working in that program only with integer- not long-values and I assume that 2 integers together get bigger than the highest possible integer +-2'147'483'647).

Is there a numeric approach (from the value I see) to get back the two int-values?

I have never tried that and I appreciate any hint!

1

1 Answers

1
votes

That is a easy one. You got your 64-bit value. The upper 32-bit is one value, the lower another.

The trick is to get the values into position to a cast to a 32-bit integer works. So casting your 64-bit value to a integer and storing it in a integer variable, will give you the lower 32-bit value right away.

For the upper value you need to do some shifting. You need to move the upper values by 32bit to the right to get them into position.

So basically:

uint64 longValue = /* Your long value. */;
uint32 firstIntValue = (uint32) longValue;
uint32 secondIntValue = (uint32) (longValue >> 32);

As the cast will discard all bits not fitting into the new variable that should work just fine.

EDIT: And as requested by comment. Also the other way round:

uint64 longValue = secondIntValue;
longValue = longValue << 32; /* If its C: longValue <<= 32; */
longValue = longValue | firstIntValue; /* If its C: longValue |= firstIntValue; */

The idea here is to first put the the integer that is supposed to end up in the higher bits to the 64-bit storage and move them with the shift to the up bits. After that place the lower value with a OR operation in the lower bits. You can't perform a simple assignment in the last operation because that would kill the upper bits.

Just as additional information. You can get around all that shifting entirely in case you are able to use unions and structs in the language you are using. If its plain C that is possible.