Visual Basic 2008 9.0 .NET Examples and Ebook

Introduction to Visual Basic

Vorig Onderwerp

New in Visual Basic 2008 - 9.0

|

Arrays

Volgend Onderwerp

Operators

Vorig Onderwerp

Boolean Datatype and Expressions

|

Datatypes

Volgend Onderwerp
Operator Precedence

Operator Precedence

Compound Assignment Operators

Compound Assignment Operators

Logical Bitwise Operators

Logical Bitwise Operators

Why Use Bitwise Operators

Why Use Bitwise Operators

Bitshift Operators

Bitshift Operators

Bitshift and Assignment Operators

Bitshift and Assignment Operators

Why Use Bitshift Operators

Why Use Bitshift Operators

Exercises

Exercises



Operator Precedence


An expression can be composed of many subexpressions combined with different operators. Some subexpressions are evaluated before other subexpressions are evaluated. The order in which these subexpressions are evaluated is based on the priority of the used operator.

The two operators with highest priority are ^ and - ( ^ has a higher priority than - ) :


    1 -> '^' ( exponentiation )
    2 -> '-' ( unary negation )

The order in which expressions combined with these operators are evaluated can be confusing, some examples to illustrate this :


Module Example1
    Sub Main()
        Dim x As Integer = 2
        Dim y As Integer = 3
        '
        Console.WriteLine(x ^ -y)
        '
        y = -3
        '
        Console.WriteLine(x ^ -y)
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 0,125
 8

 'x ^ -y' with 'x' 2 and 'y' 3  -> 2 ^ -3 = 1 / (2 ^ 3) = 0.125
 'x ^ -y' with 'x' 2 and 'y' -3 -> 2 ^ +3 =             = 8

Before the power can be calculated, then y has to be negated.


Module Example2
    Sub Main()
        Dim x As Integer = -2
        Dim y As Integer = 4
        '
        Console.WriteLine(-x ^ y)
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 -16

 '-x ^ y' with 'x' -2 and 'y' -> -(-2 ^ 4) = -16

In normal mathematics this would result in +16.

The exponential operator precedes ( in priority ) the negation operator.


 Priority List :

 1. arithmetic and concatenation operators :

    1.a -> '^' ( exponentiation )
    1.b -> '-' ( unary negation )
    1.c -> '*' ( multiplication ) and / ( division )
    1.d -> '\' ( integer division )
    1.e -> 'Mod' ( modulus )
    1.f -> '+' ( addition ) and - ( subtraction )
    1.g -> '&' ( string concatenation )

 2. comparison operators, with identical priority :

    -> '=', '<>', '<', '<=', '>' and '>='

 3. logical operators :

    3.a -> 'Not' ( negation )
    3.b -> 'And' and 'AndAlso' ( conjunction )
    3.c -> 'Or', 'OrElse' and 'Xor' ( disjunction )

When on the same line, the operators have identical priority. These will be evaluated from left to right.

Parentheses can be used to alter the priority. Often these are also used for readability.


Module Example3
    Sub Main()
        Console.WriteLine(Not 10 * -4 / 2 ^ 2 + 11 = 8 Mod 10 \ -5 ^ 2 / 5 + 1 _
                          OrElse -8 ^ -2 <= 1 AndAlso True = False)
        ' exponentiation and unary negation :
        ' 2 ^ 2 -> 4
        ' -5 ^ 2 -> -(5 ^ 2) -> -25
        ' -8 ^ -2 -> -(8 ^ -2) -> -0.015625
        Console.WriteLine(Not 10 * -4 / 4 + 11 = 8 Mod 10 \ -25 / 5 + 1 _
                          OrElse -0.015625 <= 1 AndAlso True = False)
        ' multiplication :
        ' 10 * -4 -> -40
        Console.WriteLine(Not -40 / 4 + 11 = 8 Mod 10 \ -25 / 5 + 1 _
                          OrElse -0.015625 <= 1 AndAlso True = False)
        ' division :
        ' -40 / 4 -> -10
        ' -25 / 5 -> -5
        Console.WriteLine(Not -10 + 11 = 8 Mod 10 \ -5 + 1 _
                          OrElse -0.015625 <= 1 AndAlso True = False)
        ' integer division :
        ' 10 \ -5 -> -2
        Console.WriteLine(Not -10 + 11 = 8 Mod -2 + 1 _
                          OrElse -0.015625 <= 1 AndAlso True = False)
        ' modulus
        ' 8 Mod -2 -> 0
        Console.WriteLine(Not -10 + 11 = 0 + 1 _
                          OrElse -0.015625 <= 1 AndAlso True = False)
        ' addition and subtraction :
        ' -10 + 11 -> 1
        ' 0 + 1 -> 1
        Console.WriteLine(Not 1 = 1 OrElse -0.015625 <= 1 AndAlso True = False)
        ' comparison :
        ' 1 = 1 -> True
        ' -0.015625 <= 1 -> True
        ' True = False -> False
        Console.WriteLine(Not True OrElse True AndAlso False)
        ' negation :
        ' Not True -> False
        Console.WriteLine(False OrElse True AndAlso False)
        ' conjunction :
        ' True AndAlso False -> False
        Console.WriteLine(False OrElse False)
        ' disjunction :
        ' False OrElse False -> False
        Console.WriteLine(False)
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Klik hier om terug naar boven te gaan.  Up



Compound Assignment Operators


Although we have only used assignmentoperator =, other assignmentoperators exist.

Operator += for instance will combine an addition with an assignment :


 value += 1

is identical to


 value = value + 1

Other combined ( numeric ) operators are -=, *=, /=, \= and ^=.


Module Example4
    Sub Main()
        Dim value As Integer = 2
        '
        value *= 3 + 4                                                     ' (1)
        '
        Console.WriteLine(value)
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 14

Line (1) can also be written as :


 value = value * (3 + 4)

For Strings a comparison operator exists : &=.


Module Example5
    Sub Main()
        Dim message As String = "Hello"
        '
        message &= " World !"
        '
        Console.WriteLine(message)
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 Hello World !

Klik hier om terug naar boven te gaan.  Up



Logical Bitwise Operators


Logical operators Not, And, Or and Xor can handle integral operands in a bitwise fashion. These bitwise operations handle the operands in binary format.


Module Example6
    Sub Main()
        Console.WriteLine(7 And 10)
        Console.WriteLine(7 Or 10)
        Console.WriteLine(7 Xor 10)
        '
        Console.WriteLine(7 And Not 7)
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 2
 15
 13
 0

The corresponding bits ( of the binary format ) of the operands are used for the operation :


 X     Y      X And Y     X Or Y      X Xor Y      Not X
 0     0            0          0            0          1
 0     1            0          1            1          1
 1     0            0          1            1          0
 1     1            1          1            0          0

For And, Or and Xor :


                             111 And 1010  111 Or 1010  111 Xor 1010
 Binary  :   111      1010           0010         1111          1101
 Decimal :     7        10              2           15            13

For Not


 Decimal : 7
 =
             sign bit      value bits
 Binary  :   0             000 0000 0000 0000 0000 0000 0000 0111

 Not 7
 =
             sign bit      value bits
 Binary  :   1             111 1111 1111 1111 1111 1111 1111 1000
 Decimal : -8

 7 And Not 7
 Binary :
     0000 0000 0000 0000 0000 0000 0000 0111
 And
     1111 1111 1111 1111 1111 1111 1111 1000
 =
     0000 0000 0000 0000 0000 0000 0000 0000
 Decimal : 0

The 'AndAlso' and 'OrElse' operators don't support bitwise operations.

Every operand of a bitwise operator needs to be an integral value.


Klik hier om terug naar boven te gaan.  Up


Why Use Bitwise Operators


Although nowadays programs rarely use data-units smaller then one byte, it could happen you want to handle individual bits. Bitwise operations can be used for this type of situations.

Saving memory and performance improvement are the main advantages.

Suppose we need to manage the state of a "tamagotchi". Possible states are "happy", "thirsty", "hungry", and "tired".

A Boolean variable could be used to represent a state.

An alternative would be to combine all individual states into one variable.

This is how the states could be represented :


    state :    binary representation :     decimal value :
    "happy"                       0001                   1
  "thirsty"                       0010                   2
   "hungry"                       0100                   4
    "tired"                       1000                   8

Decimal value 4 indicates that the tamagotchi is hungry, but also that the tamagotchi is not happy, thirsty or tired.

Decimal value 9 indicates that the tamagotchi is happy and tired, and not thirsty or hungry.


Module Example7
    Sub Main()
        Dim tamagotchiState As Integer = 5
        ' ...
        If (tamagotchiState And 1) = 1 Then Console.WriteLine("happy")
        If (tamagotchiState And 2) = 2 Then Console.WriteLine("thirsty")
        If (tamagotchiState And 4) = 4 Then Console.WriteLine("hungry") '    (1)
        If (tamagotchiState And 8) = 8 Then Console.WriteLine("tired")
        Console.WriteLine()
        '
        Console.WriteLine("making tamagotchi not hungry ...")
        tamagotchiState = tamagotchiState And Not 4                        ' (2)
        Console.WriteLine()
        '
        If (tamagotchiState And 1) = 1 Then Console.WriteLine("happy")
        If (tamagotchiState And 2) = 2 Then Console.WriteLine("thirsty")
        If (tamagotchiState And 4) = 4 Then Console.WriteLine("hungry")
        If (tamagotchiState And 8) = 8 Then Console.WriteLine("tired")
        Console.WriteLine()
        '
        Console.WriteLine("making tamagotchi thirsty ...")
        tamagotchiState = tamagotchiState Or 2                             ' (3)
        Console.WriteLine()
        '
        If (tamagotchiState And 1) = 1 Then Console.WriteLine("happy")
        If (tamagotchiState And 2) = 2 Then Console.WriteLine("thirsty")
        If (tamagotchiState And 4) = 4 Then Console.WriteLine("hungry")
        If (tamagotchiState And 8) = 8 Then Console.WriteLine("tired")
        Console.WriteLine()
        '
        Console.WriteLine("making tamagotchi happy, hungry and tired ...")
        tamagotchiState = tamagotchiState Or 1 Or 4 Or 8
        Console.WriteLine()
        '
        If (tamagotchiState And 1) = 1 Then Console.WriteLine("happy")
        If (tamagotchiState And 2) = 2 Then Console.WriteLine("thirsty")
        If (tamagotchiState And 4) = 4 Then Console.WriteLine("hungry")
        If (tamagotchiState And 8) = 8 Then Console.WriteLine("tired")
        Console.WriteLine()
        '
        Console.WriteLine("making tamagotchi not hungry and not tired ...")
        tamagotchiState = tamagotchiState And Not 4 And Not 8
        Console.WriteLine()
        '
        If (tamagotchiState And 1) = 1 Then Console.WriteLine("happy")
        If (tamagotchiState And 2) = 2 Then Console.WriteLine("thirsty")
        If (tamagotchiState And 4) = 4 Then Console.WriteLine("hungry")
        If (tamagotchiState And 8) = 8 Then Console.WriteLine("tired")
        Console.WriteLine()
        '
        Console.WriteLine("inverting states ...")
        tamagotchiState = Not tamagotchiState
        Console.WriteLine()
        '
        If (tamagotchiState And 1) = 1 Then Console.WriteLine("happy")
        If (tamagotchiState And 2) = 2 Then Console.WriteLine("thirsty")
        If (tamagotchiState And 4) = 4 Then Console.WriteLine("hungry")
        If (tamagotchiState And 8) = 8 Then Console.WriteLine("tired")
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

The And operator can be used to check whether the tamagotchi is in a particular state (1).

The expression tamagotchiState And 4 will only evaluate to 4 if the third bit from the right of tamagotchiState is 1.
So (tamagotchiState And 4) = 4 will only evaluate to True if the tamagotchi is in that state.

Generally :


 If (tamagochiState And state) = state Then
     ... tamagochi is in state ...
 Else
     ... tamagochi is not in state ...
 End If

For line (1) :


 tamagotchiState    5       0101
                                   And
 "hungry"           4       0100
                                   =
                            0100

When we want to remove the individual state hungry from the tamagotchi we can combine the old state with the negation of the state to remove (2). Whether the tamagotchi is hungry or not, the result will be not hungry.


 "hungry" = 4 = 0100 -> Not 4 = Not 0100 = 1011
 'tamagotchiState' "not hungry" = 0000 -> 0000 And 1011 = 0000 ( "not hungry" )
 'tamagotchiState'     "hungry" = 0100 -> 0100 And 1011 = 0000 ( "not hungry" )

To add the individual state thirsty, we can simple add 2 to the old state of the tamagotchi :


 tamagotchiState += 2

When the old tamagotchi state would be 2, and we add 2, the result is 4, or "hungry" and not "not thirty".

To add individual state thirsty ( 2 ) we can :


 tamagotchiState = tamagotchiState Or 2

The result will always contain state thirsty :


 "thirsty" = 2 = 0010
 'tamagotchiState' "not thirsty" = 0000 -> 0000 Or 0010 = 0010 ( "thirsty" )
 'tamagotchiState'     "thirsty" = 0010 -> 0010 Or 0010 = 0010 ( "thirsty" )

Klik hier om terug naar boven te gaan.  Up


Bitshift Operators


Bitshift operators >> and << shift the bits of an integral operand ( left operand ) to the right ( >> ) of left ( << ). How many positions the bits are shifted is defined by the right operand.


Module Example8
    Sub Main()
        Console.WriteLine(7 << 2)
        Console.WriteLine(7 >> 1)
        '
        Dim number As Integer = 7
        number <<= 2                                                       ' (1)
        Console.WriteLine(number)
        number = 7
        number >>= 1                                                       ' (2)
        Console.WriteLine(number)
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 28
 3
 28
 3

When the bits of 111 ( decimal 7 ) are shifted 2 positions to the left, the result is 11100 ( decimal 28 ). The extra bits on the right, are zero bits.
Shifting 1 bit to the left, is equal to multiplying the value with 2.

When the bits of 111 ( decimal 7 ) are shifted 1 position to the right, the result is 11 ( decimal 3 ).
Shifting 1 bit to the right, is equal to dividing the value by 2.

These forms of multiplication ( by 2 ) and dividing ( by 2 ) are more efficient than the normal multiplication and division operations.


Klik hier om terug naar boven te gaan.  Up


Bitshift and Assignment Operators


<<= ( see line (1) ) and >>= ( see line (2) )


Klik hier om terug naar boven te gaan.  Up


Why Use Bitshift Operators


Suppose we need to know the position of the rightmost one-bit of a given value. The operators And and >> could be used to determine that position (1).

An alternative would be to count how many time one can divide the value by 2 until the remainder of the division by 2 is 0 (2).


Module Example9
    Sub Main()
        Dim value As Integer
        Dim position As Integer
        Dim counter As Integer
        Dim start As Integer
        '
        value = 12
        position = 1
        Do While (value And 1) = 0                                        ' (1)
            value >>= 1
            position += 1
        Loop
        Console.WriteLine("12 : Bit at position " & position & _
                          " from the right is 1.")
        '
        value = 12
        position = 1
        Do While value Mod 2 <> 1                                         ' (2)
            value /= 2
            position += 1
        Loop
        Console.WriteLine("12 : Bit at position " & position & _
                          " from the right is 1.")
        '
        start = Environment.TickCount()
        For counter = 1 To 10000000                                       ' (3)
            value = counter
            position = 0
            '
            Do While (value And 1) = 0                                    ' (1)
                value >>= 1
                position += 1
            Loop
        Next
        Console.WriteLine("Bitwise calculation done in " & _
                          Environment.TickCount() - start & " tickcounts.")
        '
        start = Environment.TickCount()
        For counter = 1 To 10000000                                       ' (3)
            value = counter
            position = 0
            '
            Do While value Mod 2 <> 1                                     ' (2)
                value /= 2
                position += 1
            Loop
        Next
        Console.WriteLine("Normal calculation done in " & _
                          Environment.TickCount() - start & " tickcounts.")
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 12 : Bit at position 3 from the right is 1.
 12 : Bit at position 3 from the right is 1.
 Bitwise calculation done in 125 tickcounts.
 Normal calculation done in 499 tickcounts.

The above output can be slightly different on your system, but you will see how the bitwise calculation (1) is done a lot faster than the normal _-
calculation (2).


Klik hier om terug naar boven te gaan.  Up


Exercises


Task :

Try to simplify following conditional expressions.

You can do this by using a truth table.


 -> p Or (p And q)
 -> p And (p Or q)
 -> p And ((Not p) Or q)
 -> p Or Not p And q
 -> Not p Or p And q
 -> Not p Or p And Not q

Solution :


 -> p Or (p And q)

 p     | q     | p And q | p Or (p And q)
 True  | True  | True    | True
 True  | False | False   | True
 False | True  | False   | False
 False | False | False   | False

Column 1 and column 4 have identical results, so :


 p Or (p And q) = p

 -> p And (p Or q)

 p     | q     | p Or q | p And (p Or q)
 True  | True  | True   | True
 True  | False | True   | True
 False | True  | True   | False
 False | False | False  | False

Column 1 and column 4 have identical results, so :


 p And (p Or q) = p

 -> p And ((Not p) Or q)

 p     | q     | Not p | (Not p) Or q | p And ((Not p) Or q)
 True  | True  | False | True         | True
 True  | False | False | False        | False
 False | True  | True  | True         | False
 False | False | True  | True         | False

Column 5 shows us how the result is only True if p and q are True, just like the result of p And q would be :


 p     | q     | p And ((Not p) Or q) | p And q
 True  | True  | True                 | True
 True  | False | False                | False
 False | True  | False                | False
 False | False | False                | False

Column 3 and column 4 have identical results, so :


 p And ((Not p) Or q) = p And q

 -> p Or Not p And q

 p     | q     | Not p | Not p And q | p Or Not p And q
 True  | True  | False | False       | True
 True  | False | False | False       | True
 False | True  | True  | True        | True
 False | False | True  | False       | False

Column 5 shows us how the result is only False if p and q are False, just like the result of p Or q would be :


 p     | q     | p Or Not p And q | p Or Q
 True  | True  | True             | True
 True  | False | True             | True
 False | True  | True             | True
 False | False | False            | False

Column 3 and column 4 have identical results, so :


 p Or Not p And q = p Or q

 -> Not p Or p And q

 p     | q     | Not p | p And q | Not p Or p And q
 True  | True  | False | True    | True
 True  | False | False | False   | False
 False | True  | True  | False   | True
 False | False | True  | False   | True

For the row with result False you could state :


 Not p Or p And q = False

only if


 p and Not q

 p     | q     | Not q | p And Not q | Not p Or p And q
 True  | True  | False | False       | True
 True  | False | True  | True        | False
 False | True  | False | False       | True
 False | False | True  | False       | True

Column 4 is the negation of column 5, so :


 Not p Or p And q = Not (p And Not q) = Not p Or q

 -> Not p Or p And Not q

 p     | q     | Not p | Not q | p And Not q | Not p Or p And Not q
 True  | True  | False | False | False       | False
 True  | False | False | True  | True        | True
 False | True  | True  | False | False       | True
 False | False | True  | True  | False       | True

Only for row p And q ( p is True and q is True ) the result is False, so :


 Not p Or p And Not q

is always True if


 Not (p And q)

or


 Not p Or Not q

Task :


What will be the output of following module ?


Module Exercise2Task
    Sub Main()
        Dim value1, value2, value3 As Integer
        '
        value1 += 5
        value2 -= value1 * 6 + 1
        value3 += value1 + 5 * value2
        value3 *= value3 / -3
        value1 /= 1 / (value2 + 41)
        value2 \= 10 + value1 / 5
        '
        Console.WriteLine(value1) ' ?
        Console.WriteLine(value2) ' ?
        Console.WriteLine(value3) ' ?
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Solution :


Module Exercise2Solution
    Sub Main()
        Dim value1, value2, value3 As Integer
        '
        value1 += 5
        ' value1 = value1 + 5
        '         = 0 + 5
        '         = 5
        value2 -= value1 * 6 + 1
        ' value2 = value2 - (value1 * 6 + 1)
        '         = 0 - (5 * 6 + 1)
        '         = 0 - (30 + 1)
        '         = -31
        value3 += value1 + 5 * value2
        ' value3 = value3 + (value1 + 5 * value2)
        '         = 0 + (5 + 5 * -31)
        '         = 0 + (5 + -155)
        '         = 0 + -150 = -150
        value3 *= value3 / -3
        ' value3 = value3 * (value3 / -3)
        '         = -150 * (-150 / -3)
        '         = -150 * 50
        '         = -7500
        value1 /= 1 / (value2 + 41)
        ' value1 = value1 / (1 / (value2 + 41))
        '         = 5 / (1 / (-31 + 41))
        '         = 5 / (1 / 10)
        '         = 50
        value2 \= 10 + value1 / 5
        ' value2 = value2 \ (10 + value1 / 5)
        '         = -31 \ (10 + 50 / 5)
        '         = -31 \ (10 + 10)
        '         = -31 \ 20
        '         = -1
        '
        Console.WriteLine(value1) ' 50
        Console.WriteLine(value2) ' -1
        Console.WriteLine(value3) ' -7500
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 50
 -1
 -7500




This version ( published on 2008-06-24 ) is printed from http://www.studyvb.com, visit the website for more recent information.

Updated On : 2008-01-22

Download Broncode

Published On : 2008-06-24

Operators

Vorig Onderwerp

Boolean Datatype and Expressions

|

Datatypes

Volgend Onderwerp

Introduction to Visual Basic

Vorig Onderwerp

New in Visual Basic 2008 - 9.0

|

Arrays

Volgend Onderwerp
Nederlands  Nederlands

Add to favorites (IE).