Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a ulong into two uint variables in c#

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.

like image 912
JoeGeeky Avatar asked Dec 16 '22 05:12

JoeGeeky


2 Answers

Two options:

  • use unsafe code or abuse an explicit-layout struct (as a union) to rip it into pieces silently
  • use shift operations

I'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.

like image 144
Marc Gravell Avatar answered Dec 18 '22 18:12

Marc Gravell


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.

like image 27
shf301 Avatar answered Dec 18 '22 20:12

shf301