Convert Sbyte to integer in c#

I can't seem to figure out a way to convert an sbyte back to original integer value.

int k = 148;
sbyte t = (sbyte)k;
int asd = Convert.ToInt32(t);

The value of asd is -108. How can I convert the sbyte back to int to get the original value of 148?

Thanks

Jon Skeet
people
quotationmark

Assuming you want the result to be in the range 0-255 inclusive, the simplest approach is:

int asd = t & 0xff;

This will promote k to an int, then take just the bottom 8 bits, leaving all the top 24 bits as 0.

However, I'd question why you'd want to use sbyte for this in the first place. It's very very rarely a good idea - one of the design flaws of Java (in my view) was to make byte a signed type. If you want to represent byte values, byte would be more appropriate.

people

See more on this question at Stackoverflow