按位转换会产生错误的期望值

问题描述 投票:0回答:1

我正在尝试从字节缓冲区转换回对应的 ulong,但无法重新创建该值...我一定是盲目的或者在这里做错了什么:(

ulong us = (ulong)(millisecondsSinceUnixEpoch * 1000.0);

// xxxxxxxx-xxxx-0000-0000-000000000000
_buffer[0] = (byte)(us >> 40);
_buffer[1] = (byte)(us >> 32);
_buffer[2] = (byte)(us >> 24);
_buffer[3] = (byte)(us >> 16);
_buffer[4] = (byte)(us >> 8);
_buffer[5] = (byte)us;


ulong reUs = ((ulong)_buffer[0] << 40) |
             ((ulong)_buffer[1] << 32) |
             ((ulong)_buffer[2] << 24) |
             ((ulong)_buffer[3] << 16) |
             ((ulong)_buffer[4] << 8) |
             _buffer[5];

Debug.WriteLine(us);
Debug.WriteLine(reUs);

结果:

1691334871851000(美国)

2485011587064(reU)

期待(reUs == us)

c# bit-manipulation bitwise-operators bit-shift
1个回答
0
投票

正如回复所说,我丢失了一个字节,导致数字不匹配。这是由于我错误的计算将秒转换为毫秒,这是没有必要的,因为该值已经以毫秒为单位!正确的代码是:

    _buffer[0] = (byte)(millisecondsSinceUnixEpoch >> 40);
    _buffer[1] = (byte)(millisecondsSinceUnixEpoch >> 32);
    _buffer[2] = (byte)(millisecondsSinceUnixEpoch >> 24);
    _buffer[3] = (byte)(millisecondsSinceUnixEpoch >> 16);

    _buffer[4] = (byte)(millisecondsSinceUnixEpoch >> 8);
    _buffer[5] = (byte)millisecondsSinceUnixEpoch;


    ulong reUs = ((ulong)_buffer[0] << 40) |
                 ((ulong)_buffer[1] << 32) |
                 ((ulong)_buffer[2] << 24) |
                 ((ulong)_buffer[3] << 16) |
                 ((ulong)_buffer[4] << 8) |
                 _buffer[5];
© www.soinside.com 2019 - 2024. All rights reserved.