简体   繁体   English

在后台将字节转换为INT64

[英]Byte conversion to INT64, under the hood

Good day. 美好的一天。 For a current project I need to know how datatypes are represented as bytes. 对于当前项目,我需要知道如何将数据类型表示为字节。 For example, if I use : 例如,如果我使用:

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

I get the values 244,1,0,0,0,0,0,0. 我得到值244,1,0,0,0,0,0,0。 I get that it is a 64 bit value, and 8 bits go int a bit, thus are there 8 bytes. 我得到它是一个64位值,并且8位变为int位,因此有8个字节。 But how does 244 and 1 makeup 500? 但是244和1个化妆500怎么办? I tried Googling it, but all I get is use BitConverter. 我尝试了谷歌搜索,但是我得到的只是使用BitConverter。 I need to know how the bitconverter works under the hood. 我需要知道位转换器在幕后的工作方式。 If anybody can perhaps point me to an article or explain how this stuff works, it would be appreciated. 如果有人可以将我指向某篇文章或解释这些东西是如何工作的,将不胜感激。

It's quite simple. 这很简单。

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

If you need source code you should check Microsoft GitHub since implementation is open source :) https://github.com/dotnet 如果您需要源代码,则应检查Microsoft GitHub,因为实现是开源的:) https://github.com/dotnet

From the 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM