首页 > 解决方案 > 如何在 C# 中表示 PTP 时间戳?

问题描述

我有一个通过 tcp 套接字进入的 80 位 PTP (IEEE 1588v2) 时间戳。

PTP 时间戳由 48 位无符号整数(秒)和 32 位无符号整数(纳秒)组成。

所以我的问题是我如何在 c# 中表示这个时间戳,因为没有 UInt48?

标签: c#ptp

解决方案


您可以使用 10 个字节(=80 位)的数组并提取 UIint64 几秒钟:

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));
}

推荐阅读