Search code examples
c#c++bitconverter

About the "GetBytes" implementation in BitConverter


I've found that the implementation of the GetBytes function in .net framework is something like:

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

I'm not so sure I understand the full details of these two lines:

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

Could someone provide a more detailed explanation here? And how should I implement this function in standard C++?


Solution

  • Could someone provide a more detailed explanation here?

    The MSDN documentation for fixed comes with numerous examples and explanation -- if that's not sufficient, then you'll need to clarify which specific part you don't understand.


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