How to represent a PTP Timestamp in c#?

434 Views Asked by At

I am have an 80bit PTP (IEEE 1588v2) timestamp that comes in via a tcp socket.

The PTP timestamp consists of a 48 bit unsigned int for seconds and a 32bit unsigned int for nanoseconds.

So my question is how do I represent this timestamp in c# as there is no UInt48?

1

There are 1 best solutions below

0
On

You could use an array of 10 bytes (=80 bits) and extract UIint64 for seconds:

static void Main(string[] args)
{
    // Setup fake data
    var ptp = new byte[10]; //10 x bits 
    ptp[10 - 1] = 1; // Nanoseconds = last 32 bits 
    ptp[6 - 1] = 42; // Seconds = first 48 bits (48 = 6x8)

    var duration = Decode(ptp);

    Console.WriteLine($"s: {duration.Seconds}, ns: {duration.Nanoseconds}"); // s: 42, ns: 1
}

private static (UInt64 Seconds, UInt32 Nanoseconds) Decode(byte[] ptp)
{
    // Create an 8 byte array for UInt64 
    // by copying the first 6 bytes to to a new 8 byte array to poitions 2, 3, ..., 7
    // and leave [0] and [1] as zeroes
    var forSeconds = new byte[8];
    Array.Copy(sourceArray: ptp, sourceIndex: 0, destinationArray: forSeconds, destinationIndex: 2, length: 6);
    if (BitConverter.IsLittleEndian) Array.Reverse(forSeconds);

    // Nanoseconds are easier
    // Take last 4 bytes from the initial 10 byte array.
    var forNanoseconds = ptp.AsSpan<byte>().Slice(start: 6, length: 4);
    if (BitConverter.IsLittleEndian) forNanoseconds.Reverse();

    return (Seconds: BitConverter.ToUInt64(forSeconds), 
            Nanoseconds: BitConverter.ToUInt32(forNanoseconds));
}