Search code examples
vb.netbinarybitsigned

Why does a negative SByte number have 16 bits in VB.Net?


I asked a question earlier about comparing numbers using the "And" comparison operator in If Statements and now I have been toying around with getting my head wrapped around bitwise operators. So I have written a very basic code that will allow me to see the conversion of any decimal number in binary format.

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    MsgBox(ConvertToBinary(-1))
End Sub

Public Function ConvertToBinary(ByVal someInteger As SByte) As String
    Dim converted As String = Convert.ToString(someInteger, 2) '.PadLeft(8, "a"c)
    Return converted
End Function

Notice here that I am using SByte as the paramerter - which should only contain 8 bits right? However, the message box that appears has 16 bits assigned to negative numbers. Positive numbers have the correct 8.


Solution

  • There is no Convert.ToString overload that takes an SByte, so the SByte is being implicitly converted to a Short.