Reputation: 1007
Previous question was to encode two Int32
into one Int64
[C# - Making one Int64 from two Int32s
Question: How to decode one Int64
back to two Int32
?
Upvotes: 3
Views: 3854
Reputation: 13907
Here's a (cheap) solution that will work for both conversions.
[StructLayout(LayoutKind.Explicit)]
public struct UnionInt64Int32 {
public UnionInt64Int32(Int64 value) {
Value32H = 0; Value32L = 0;
Value64 = value;
}
public UnionInt64Int32(Int32 value1, Int32 value2) {
Value64 = 0;
Value32H = value1; Value32L = value2;
}
[FieldOffset(0)] public Int64 Value64;
[FieldOffset(0)] public Int32 Value32H;
[FieldOffset(4)] public Int32 Value32L;
}
An obvious drawback to this though, it's unportable. The Value32H and value32L will be reversed on different endian platforms.
Upvotes: 3
Reputation: 1502476
Something like this:
long x = ...;
int a = (int) (x & 0xffffffffL);
int b = (int) (x >> 32);
It's just possible that the masking in the first form is unnecessary... I can never remember the details around narrowing conversions and signed values, which is why I've included it :)
Upvotes: 8