字节转换为 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 是如何工作的。如果有人能给我指出一篇文章或解释这些东西是如何工作的,我们将不胜感激。
来自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;
}
很简单。
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
美好的一天。对于当前的项目,我需要知道数据类型如何表示为字节。例如,如果我使用 :
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 是如何工作的。如果有人能给我指出一篇文章或解释这些东西是如何工作的,我们将不胜感激。
来自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;
}
很简单。
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