gpt4 book ai didi

c# - 关于 BitConverter 中的 "GetBytes"实现

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:38:47 25 4
gpt4 key购买 nike

我发现 .net 框架中 GetBytes 函数的实现是这样的:

public unsafe static byte[] GetBytes(int value)
{
byte[] bytes = new byte[4];
fixed(byte* b = bytes)
*((int*)b) = value;
return bytes;
}

我不太确定我理解这两行的全部细节:

   fixed(byte* b = bytes)
*((int*)b) = value;

有人可以在这里提供更详细的解释吗?我应该如何在标准 C++ 中实现此功能?

最佳答案

Could someone provide a more detailed explanation here?

MSDN documentation for fixed随附大量示例和解释——如果这还不够,那么您需要澄清您不理解的具体部分。


And how should I implement this function in standard C++?

#include <cstring>
#include <vector>

std::vector<unsigned char> GetBytes(int value)
{
std::vector<unsigned char> bytes(sizeof(int));
std::memcpy(&bytes[0], &value, sizeof(int));
return bytes;
}

关于c# - 关于 BitConverter 中的 "GetBytes"实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8675248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com