Performing bit manipulation in C # can sometimes be inconvenient, especially when it comes to signed values. You must use unsigned values ββwhenever you plan to manipulate bits. Unfortunately, this will not give the most beautiful code.
const long LOW_MASK = ((1L << 32) - 1); long value = unchecked((long)0xDEADBEEFFEEDDEAD); int valueHigh = (int)(value >> 32); int valueLow = (int)(value & LOW_MASK); long reconstructed = unchecked((long)(((ulong)valueHigh << 32) | (uint)valueLow));
If you want a more convenient way to do this, get the raw bytes over time and get the corresponding numbers from the bytes. Converting to / from representations does not change much.
long value = unchecked((long)0xDEADBEEFFEEDDEAD); byte[] valueBytes = BitConverter.GetBytes(value); int valueHigh = BitConverter.ToInt32(valueBytes, BitConverter.IsLittleEndian ? 4 : 0); int valueLow = BitConverter.ToInt32(valueBytes, BitConverter.IsLittleEndian ? 0 : 4); byte[] reconstructedBytes = BitConverter.IsLittleEndian ? BitConverter.GetBytes(valueLow).Concat(BitConverter.GetBytes(valueHigh)).ToArray() : BitConverter.GetBytes(valueHigh).Concat(BitConverter.GetBytes(valueLow)).ToArray(); long reconstructed = BitConverter.ToInt64(reconstructedBytes, 0);
Jeff mercado
source share