Sunday, April 22, 2018

Converting a 16 bit twos complements value to decimal value : algorithm and implementation

Converting a 16 bits twos complement value to a decimal value equivalent. In this tutorial a simple algorithm and implementation are shared.

Main sub

Sub Main
    
 Dim result As Short = 0
 Dim value = 50
 result = GetDecimalValue(value)
 Console.WriteLine("Decimal value of " & value & " is "& result)
End Sub

  


Get the sign sub


Function GetSign16Bit( value)
'This function returns -1 if the 16 bits value is negative and 1 if it is zero or positive
   Dim sign = 0
   value = value/ 256    'Get the left most byte
   value = value / 16    'Get the leftmost 4-bits
   value = value / 4     'Get the leftmost 2-bits
   value = value / 2     'Get the  leftmost 1-bit
    If  value  >=1 Then
         sign = -1
    Else
          sign= 1
    End If
   Return sign
End Function

  


Converting to decimal value sub


Function GetDecimalValue(value)
'This function takes the twos complement of a 16 bits value and  return the equivalent decimal value
' We know that, 2^16 =65536
    Dim ValueOneComplement, Result 
 If  GetSign16Bit(value) = 1 Then  ' Positive number
         Result = value
    Else                              'Negative number
            ValueOneComplement = Not  value  ' get the one's complement of the value
            Result =  (65536  + ValueOneComplement ) +1 
            Result = - Result  'Make the value negative by prefixing it with minus
    End If
 Return Result
End Function

  

This is just a trick, hope it paved your way out. 

No comments:

Post a Comment