I have a series of ulong
instances, each of which contains two separate values. The first 4 bytes represents one uint
value and the second 4 bytes represent another. What is the most efficient means of parsing the ulong
into two uint
variables? This will be occurring in tight loops so I’m looking for the fastest possible pattern.
Two options:
unsafe
code or abuse an explicit-layout struct
(as a union) to rip it into pieces silentlyI'd usually prefer the latter; i.e.
uint x = (uint)(value & 0xFFFFFFFF), y = (uint)((value >> 32)&0xFFFFFFFF)
In addition to working in more environments (not all VMs allow unsafe
), this avoids any risk of confusion on a different-endian machine (using Mono, perhaps).
The unsafe
version would be something like:
uint* ptr = (uint*)(void*)&value;
uint x = ptr[0], y = ptr[1];
For which is faster: try is both options and time t! A micro-optimisation can only be evaluated in a specific code-context.
You could also so an explicitly layout a struct with overlapping fields (which is like a C union).
[StructLayout(LayoutKind.Explicit)]
struct SplitStruct
{
[FieldOffset(0)]
public ulong ulongValue;
[FieldOffset(0)]
public uint uintValue1;
[FieldOffset(4)]
public unit uintValue2;
}
Although personally I'd still use the bit shift. The explicitly laid out struct hides what's happening and is pretty obscure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With