Robert Robert - 1 month ago 15
C# Question

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 << count) - 1));
}


I'm stuck trying to convert the GetBitRange() formula to use ushort and also how to handle the twos complement.

Answer

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();
}