mc-Things

mc-Products => mc-Module => Topic started by: Nick_W on September 02, 2016, 04:59:14 pm

Title: How to construct a Signed Short from Bytes
Post by: Nick_W on September 02, 2016, 04:59:14 pm
I had some problems making a signed Short from two bytes (in a ListOfBytes). As a Short is signed, I thought the result would be signed by default - well it isn't!

This was my code:

Code: [Select]
    //**************************************************************************/
    //
    //    @brief  Reads a signed 16 bit value over I2C
    //
    //**************************************************************************/
    Public Function readS16(reg As Byte) As Integer //should return Short
        Dim result As Short = 0
        Dim value As ListOfByte = read2X8(reg)
        If value <> Nothing Then
            result = (value(0) << 8) | value(1)
            //result = value.ExtractShort(0, Endianness.Big) //not working
        End If
        Return result
    End Function

So first ExtractShort() doesn't work (although this does exactly what I want - I think). The above always returns an unsigned Short (as Integer). Even if you change the return type to Short, it still returns an unsigned Short (or Integer, not sure which).

To make it a Signed Short (or Integer) I had to manually convert it to two's compliment:

Code: [Select]
    //**************************************************************************/
    //
    //    @brief  Reads a signed 16 bit value over I2C
    //
    //**************************************************************************/
    Public Function readS16(reg As Byte) As Integer //should return Short
        Dim result As Short = 0
        Dim value As ListOfByte = read2X8(reg)
        If value <> Nothing Then
            result = (value(0) << 8) | value(1)
            //result = value.ExtractShort(0, Endianness.Big) //not working
        End If
        //convert value to 2's compliment
        If (value(0) > 0x7f) Then
            result = (~result + 1) * (-1)
        End If
        Return result
    End Function

Just thought I would point this out for anyone manipulating bytes out there. Anyone know how to use ExtractShort() or why it doesn't work in the above?

Thanks,