簡體   English   中英

在后台將字節轉換為INT64

[英]Byte conversion to INT64, under the hood

美好的一天。 對於當前項目,我需要知道如何將數據類型表示為字節。 例如,如果我使用:

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

我得到值244,1,0,0,0,0,0,0。 我得到它是一個64位值,並且8位變為int位,因此有8個字節。 但是244和1個化妝500怎么辦? 我嘗試了谷歌搜索,但是我得到的只是使用BitConverter。 我需要知道位轉換器在幕后的工作方式。 如果有人可以將我指向某篇文章或解釋這些東西是如何工作的,將不勝感激。

這很簡單。

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

源代碼

// 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