c# - 如何在 C# 中表示 PTP 时间戳?
问题描述
我有一个通过 tcp 套接字进入的 80 位 PTP (IEEE 1588v2) 时间戳。
PTP 时间戳由 48 位无符号整数(秒)和 32 位无符号整数(纳秒)组成。
所以我的问题是我如何在 c# 中表示这个时间戳,因为没有 UInt48?
解决方案
您可以使用 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));
}
推荐阅读
- python-3.x - Raspberry Pi 3b 中的 libwebp.so.6 导入错误
- typescript-typings - 键入具有来自另一个包的类型的无类型包
- clojure - 无法获取宏的值:#'clojure.core/case
- sql - SQL 包含带有分区聚合的子句
- amazon-web-services - 通过 Cloudformation 模板具有 lambda 目标的 AWS ALB
- python - Python,如何同时打印所有键的值?
- javascript - 防止背景在后台滚动
- c# - 脚本任务问题列出目录中的excel文件
- javascript - 如何防止可能的嵌套承诺?
- bash - iTerm2 & Atom - 根据 ~/.bash_profile 中的输入 bash 命令切换配置文件,寻找建议