Search code examples
c#pointersmemory-safety

Best way to copy bits from a signed to an unsigned variable of same size in C#


In C++ or C I'd either use memcpy or use pointers like this:

uint16_t b = NULL;
int16_t signed_val = -50;
uint16_t b = *(int16_t*)&signed_val;

I know C# supports pointers, but I'm trying to avoid using them in this case. I can't figure out a more sensible solution.


Solution

  • Have you tried the simple way?

    short signed_val = -50;
    ushort unsigned_val = (ushort)signed_val;
    

    unsigned_val = 65486