Skip to content
ascendedguard edited this page Dec 3, 2010 · 2 revisions

paramValue

paramValue is a special type that can be 1 or 2 bytes, depending on the contained value. Use an 0x80 mask to determine if there is a follow-up byte to read in.

Remember that in a keyValueStruct, the encoded value is doubled.

The following C# code parses a KeyValueStruct, using the 0x80 mask to check the signal bit, and bit-shifting to remove it if reading in a 2nd byte.

    /// <summary>
    /// Parses a KeyValueStruct from an expected position in a BinaryReader,
    /// returning the KeyValueStruct and advancing the reader past the object.
    /// </summary>
    /// <param name="reader">BinaryReader advanced to a point expecting a KeyValueStruct</param>
    /// <returns>The KeyValueStruct found at the current reader position.</returns>
    public static KeyValueStruct Parse(BinaryReader reader)
    {
        var kv = new KeyValueStruct { Key = reader.ReadBytes(2) };

        byte firstByte = reader.ReadByte();

        if ((firstByte & 0x80) > 0)
        {
            firstByte <<= 1; // Knock off the insignificant bit
            byte secondByte = reader.ReadByte();

            short value = BitConverter.ToInt16(new[] { firstByte, secondByte }, 0);

            value >>= 1; // Shift to the right to accomodate for the signal bit to get the true value.

            kv.Value = (short)(value / 2);
        }
        else
        {
            kv.Value = (short)(firstByte / 2);
        }

        return kv;
    }