Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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++?

like image 712
derekhh Avatar asked Dec 30 '11 01:12

derekhh


1 Answers

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;
}
like image 196
ildjarn Avatar answered Oct 16 '22 17:10

ildjarn