
void Main()
{
var id = new XID.Info(271103830593110952);
id.Dump();
}
public static class XID
{
private static long workerId = 0;
private static long sequence = 0L;
private static long lastTimestamp = -1L;
private static readonly int workerIdBits = 10;
private static readonly int sequenceBits = 22 - workerIdBits;
private static readonly int sequenceShift = workerIdBits;
private static readonly int timestampLeftShift = sequenceBits + workerIdBits;
private static readonly long workerIdMax = -1L ^ -1L << workerIdBits;
private static readonly long sequenceMax = -1L ^ -1L << sequenceBits;
private static readonly object lockObj = new object();
private static readonly DateTime start_base_time = new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static void Initialize(string data)
{
long.TryParse(data, out workerId);
}
public static long Nextval
{
get
{
lock (lockObj)
{
return nextId();
}
}
}
private static long nextId()
{
if (workerId < 1)
{
workerId = 1982;
}
workerId = workerId & workerIdMax;
long timestamp = timeGen();
if (lastTimestamp == timestamp)
{
var abc = (sequence + 1) & sequenceMax;
if (abc == 0)
{
timestamp = tillNextMillis(lastTimestamp);
}
sequence = abc;
}
else
{
sequence = 0;
}
if (timestamp < lastTimestamp)
{
throw new Exception(string.Format("Clock moved backwards. Refusing to generate id for {0} milliseconds",
lastTimestamp - timestamp));
}
lastTimestamp = timestamp;
long nextId = timestamp << timestampLeftShift | sequence << sequenceShift | workerId;
return nextId;
}
private static long tillNextMillis(long lastTimestamp)
{
long timestamp = timeGen();
while (timestamp <= lastTimestamp)
{
timestamp = timeGen();
}
return timestamp;
}
private static long timeGen()
{
return (long)(DateTime.UtcNow - start_base_time).TotalMilliseconds;
}
public class Info
{
public Info(long id)
{
var size = 64;
this.Timestamp = id >> timestampLeftShift;
this.CreateTime = start_base_time.AddMilliseconds(this.Timestamp);
var timeLen = (size - timestampLeftShift);
this.SequenceId = id << timeLen >> timeLen >> sequenceShift;
this.WorkerId = id & ((1 << sequenceShift) - 1);
}
public DateTime CreateTime { get; set; }
public long Timestamp { get; set; }
public long SequenceId { get; set; }
public long WorkerId { get; set; }
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律