Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 714
Icemanind Avatar asked Oct 16 '25 03:10

Icemanind


1 Answers

I'm just writing a C function (because I don't really know C#) that will do this using operations that I know are available in C#.

int five_bit_to_signed(int five_bit) {
     int sh = (sizeof(int)*8)-5;
     int x = five_bit << sh; // puts your sign bit in the highest bit.
     return x >> sh;  // since x is signed this is an arithmatic signed shift
}
like image 189
nategoose Avatar answered Oct 18 '25 21:10

nategoose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!