Convert ushort to string
I have a ushort that consists of two bytes.
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
Y = bits 10-0, twos complement mantissa integer.
N = bits 15-11, twos complement integer.
X = Y * 2^N
I need to ouput X as a string.
This is what I have tried:
private string ConvertLinearToString(ushort data)
{
int N;
int Y;
int X;
N = Convert.ToInt16(GetBitRange((byte)data, 0, 5));
Y = Convert.ToInt16(GetBitRange((byte)data, 6, 11));
X = Convert.ToInt16(Y * Math.Pow(2, (double)N));
return Convert.ToString(result);
}
private byte GetBitRange(byte b, int offset, int count)
{
return Convert.ToByte((b >> offset) & ((1 <<开发者_Python百科; count) - 1));
}
I'm stuck trying to convert the GetBitRange() formula to use ushort and also how to handle the twos complement.
You can get the two's complement behavior by using a left shift to throw away bits you don't want followed by a right shift to sign extend. If you implement GetBitRange using 32-bit integers like this:
private static int GetBitRange(int data, int offset, int count)
{
return data << offset >> (32 - count);
}
Then just let the ushorts get converted to ints in ConvertLinearToString:
private static string ConvertLinearToString(ushort data)
{
var n = GetBitRange(data, 16, 5);
var y = GetBitRange(data, 21, 11);
var value = y * Math.Pow(2, n);
return value.ToString();
}
Just covert your unsigned short to an integer and use the method to do the conversion.
ushort u = 10;
string s = Convert.ToString((int)u);
This solution is reasonably safe from overflow. There maybe some future version of C# where this operation would no longer be safe.
精彩评论