【问题标题】:Byte conversion to INT64, under the hood字节转换为 INT64,在引擎盖下
【发布时间】:2018-12-12 11:38:58
【问题描述】:

美好的一天。对于当前项目,我需要知道数据类型如何表示为字节。例如,如果我使用:

long three = 500;var bytes = BitConverter.GetBytes(three);

我得到的值是 244,1,0,0,0,0,0,0。我知道它是一个 64 位的值,并且 8 位进入一点,因此有 8 个字节。但是244和1是怎么组成500的呢?我试过用谷歌搜索它,但我得到的只是使用 BitConverter。我需要知道位转换器是如何工作的。如果有人可以向我指出一篇文章或解释这些东西是如何工作的,将不胜感激。

【问题讨论】:

  • 244 + 256的值是多少?您认为 1 可能意味着什么?
  • 244 + 256 * 1 + 256 * 256 * 0 + ... + 256 * ... * 256 * 0 == 500
  • 如果你不习惯那种数学,可以这样想。 123,在普通数学中,是什么意思?这意味着 1 x 10^2 + 2 x 10^1 + 3 * 10^0。除了两件事之外,您的示例完全相同。 a) 数字顺序相反。它不是 10 的幂,它是 256 的幂(因为一个字节是 8 位 - 最多可以存储 256)。跨度>
  • 太棒了,现在对我来说很有意义。非常感谢。

标签: c# byte data-conversion


【解决方案1】:

这很简单。

BitConverter.GetBytes((long)1); // {1,0,0,0,0,0,0,0};
BitConverter.GetBytes((long)10); // {10,0,0,0,0,0,0,0};
BitConverter.GetBytes((long)100); // {100,0,0,0,0,0,0,0};
BitConverter.GetBytes((long)255); // {255,0,0,0,0,0,0,0};
BitConverter.GetBytes((long)256); // {0,1,0,0,0,0,0,0}; this 1 is 256
BitConverter.GetBytes((long)500); // {244,1,0,0,0,0,0,0}; this is yours 500 = 244 + 1 * 256

如果您需要源代码,您应该查看 Microsoft GitHub,因为实现是开源的 :) https://github.com/dotnet

【讨论】:

  • 我不知道 .Net 源是开放的。我以为只有 .NetCore 是开源的。这很有帮助,谢谢。
【解决方案2】:

来自source code

// Converts a long into an array of bytes with length 
// eight.
[System.Security.SecuritySafeCritical]  // auto-generated
public unsafe static byte[] GetBytes(long value)
{
    Contract.Ensures(Contract.Result<byte[]>() != null);
    Contract.Ensures(Contract.Result<byte[]>().Length == 8);

    byte[] bytes = new byte[8];
    fixed(byte* b = bytes)
        *((long*)b) = value;
    return bytes;
}

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 2019-10-19
    • 2019-11-27
    • 2021-04-24
    • 2022-06-10
    • 1970-01-01
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多