Conversions - Boolean, Integer and Byte.

There are many parts of "language" that, while I don't really understand the underlying rules, I just accept them in my life. Here's some conversions between Boolean, Int and Byte which, while they work, I don't fully understand the rules governing them:

Dim b1 As Boolean = True
        
Dim i As Integer = b1
Dim byt As Byte = b1
' Converting Boolean's to Byte's and Int's produces different values
Debug.WriteLine(i)      ' - 1
Debug.WriteLine(byt)    ' 255

' Even though True converts to int -1 and False converts to int 0,
' casting every int value other than zero converts to boolean True
Dim i2 As Integer = 1
Dim i3 As Integer = -600001.567
Dim b2 As Boolean = CBool(i2)
Dim b3 As Boolean = CBool(i3)
Debug.WriteLine(b2)     ' True
Debug.WriteLine(b3)     ' True

8 Comments

  • Byte is unsigned, int is signed which I hope explains the first case.

    0 is conventionally False, and it's a long-standing convention that anything else is True. In particular this convention ensures that both 255 and -1 convert to True.

  • So, I guess that 255 was arbitrarily picked as the conversion amount when converting to Byte? As opposed to - say - 1 or 138? Or is there a better reason to pick 255?



    I guess that I just figured that you could convert to a value of 1 == True regardless of whether you are converting to Int's or Byte's.

  • When going into negative numbers in binary the first bit on the left is a place holder indicating sign

    and also to make addition 5 + (-1) work properly, the value is inverted ie

    11111111 is -1 for a signed 8bit number

    11111110 is -2 for a signed 8bit number



    However, 11111111 is 255 for an unsigned number.



    So all .NET does is turn on all bits on the target integer or byte when converting from boolean

  • Dim bool As Boolean

    Dim int As Integer

    'Convert a boolean to an integer

    int = Not bool

    Console.WriteLine(int)

  • I have a suspicion that the first person thought explaning the difference between signed and unsigned numbers

    Maybe he meant

    "Byte is unsigned, int is signed which I hope(If you aren't completely incompetent) explains the first case. "

  • Thankyou for your explanations.



    Unfortunately my binary skills are zero. I can see why:



    11111111 is 255 for an unsigned number



    But, I cannot understand why:



    11111111 is -1 for a signed 8bit number



    But, that's a separate problem which I can easily follow up by reading about Binary. Thanks again for your time.

  • Please fix your stylesheet!!!

  • CM... can you please expand on your comment? What, in particular, would you like to see "fixed"?

Comments have been disabled for this content.