Search code examples
c#cbinarybit-manipulationsigned

Sign extending from a constant bit width in C#


I have a value thats 5 bits in length. 4 bits determine the number and the 5th bit determines the sign, there by holding any value between -16 and +15. How can I accomplish sign extending from a constant bit width in C#? I know in C, I can use something like the follow to accomplish this:

int x; // convert this from using 5 bits to a full int
int r; // resulting sign extended number goes here
struct {signed int x:5;} s;
r = s.x = x;

How can I do something similar to this in C#?


Solution

  • It's not really clear what you mean, but it could be as simple as:

    int fiveBits = normal & 0x1f;
    

    and for the reverse:

    int normal =  fiveBits < 16 ? fiveBits : fiveBits | -32;
    

    If you could suggest some original input and desired output, that would help.