Home > Back-end >  Best way to copy bits from a signed to an unsigned variable of same size in C#
Best way to copy bits from a signed to an unsigned variable of same size in C#

Time:02-01

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.

CodePudding user response:

Have you tried the simple way?

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

unsigned_val = 65486

  •  Tags:  
  • Related