The Values of an Application

Introduction

When interacting with the computer, at times, a user might be asked to provide a value. At other times, the user might be presented with a value to manipulate. During this interaction, the values, any of them, are stored and retrieved at will. To make this possible, the computer uses its memory.

The computer memory is an area used to receive information, store it, and then make that information available when requested. The computer only makes its memory available to you. It doesn't know and cannot predict the type of value that your particular program would need. This is because one program might be made to manipulate numbers while another program might be made for names. Because the information stored in the computer can be as varied as possible, it may be segmented (the word segment is taken in its English meaning and not in its Assembly definition) in portions or various pieces.

The pieces of information stored in the computer memory come, go, and change on a regular basis. For this reason, a piece of information stored in the computer memory is called a variable. A variable is an area of the computer memory used to store a value. Because there can be many kinds of values stored in the computer memory, a variable stores only one kind of value.

The Stack

To manage the various types of values that can be used in a program, the computer is equipped with two types of memory. The Random Access Memory, also called RAM, is a type of memory that is "filled" with values when the computer comes up and while a person is using the computer. When the computer gets shut down, the RAM looses everything that was put in that memory so that the next time the computer comes up, the RAM "forgets" the values that were entered in it the previous time. In other words, when the computer boots up, the RAM is empty and new values must be entered in it.

Another type of memory that the computer uses is called Read-Only Memory (ROM). In this area, the computer stores values that "stick" in it and stay there. Such values can be called when needed and, unless they are explicitly deleted, when the computer gets shut down, the values go back to the ROM. The next time the computer comes up, the values of the ROM will be available. The values of the ROM stay there and are retrieved only when requested.

The RAM can be illustrated like a group of small boxes. When the computer boots up, or while the computer is coming up, they are empty:

RAM

Each one of these small boxes is named a bit. It can have only one of two values. From our illustrations, when the box is empty, the bit has a value of 0. When it is filled (it cannot be half-full or half-empty), it has a value of 1.

When the computer has finished booting up, some values are asked to occupy this area. In the same way, when you start a program like Notepad, it is "loaded" in this memory. This means that part of the RAM is filled with some values. Some other parts of the RAM are filled with garbage or values that don't mean anything to you:

RAM

When your application comes up, you can ask the computer to put some values for your application. Remember that you are not, or your application is not, the only one that needs to use an area of the computer memory. Because there can be so many values that different applications store, retrieve, and manipulate all day long or as long as the computer is on, the operating system reserves an area of this memory for applications like yours. To make sure there is no mess, the computer is in charge of this area of memory. When you want to store a value in that memory, you let the computer know. The computer then puts (the verb used is "push") that value in the necessary area of the memory (the computer, and not you, decides where to put the value). When the value is not used anymore, the computer removes (the verb used is "pop") that value. This allows the computer to make that area of memory available to the applications that would need it. This area of memory that the computer reserves for the various applications, and is in charge of, is called the stack.

Variable Declaration

If you want to use an area of memory of the computer, in other words if you want to store a value in that memory, you must ask the compiler to reserve a portion of memory for your value. Making this request is referred to as declaring a variable. To formulate this request, you must first type the Dim keyword:

Dim

To make this request, you must provide a name for the variable. The name of a variable is also called an identifier. When the computer reserves an area of memory, it uses a name to be able to locate that area of memory. Later on, when you want to store a value in that memory, you will communicate a name to the compiler. The compiler will know the area of memory you are referring to by its name. This means that, at the right time, the name is used by both you and the compiler to know what portion of memory you are referring to. The name itself is not stored in the memory per se. It only allows you and the compiler to access a particular area of memory.

The Name of a Variable

There are rules you should, and usually must, follow when naming your variables. The rules to follow are:

A name cannot be one of the words reserved for the Visual Basic language's own use. These words are also called keywords. Therefore, avoid using the following words to name a variable (this list includes official Visual Basic language keywords and words or expressions you should avoid):

AddHandler AddressOf Alias And AndAlso
Ansi As Assembly Auto Boolean
ByRef Byte ByVal Call Case
Catch CBool CByte CChar CDate
CDbl CDec Char CInt Class
CLng CObj Compare Const Continue
CSByte CShort CSng CStr CType
CUInt CULng CUShort Custom Date
Decimal Declare Default Delegate Dim
DirectCast Distinct Do Double Each
Else ElseIf      
End EndIf Enum Equals Erase
Error Event Exit Explicit False
Finally For Friend From Function
Get GetType GetXmlNamespace GoSub GoTo
Group By Group Join Handles If Implements
Imports In Inherits Integer Interface
Into Is IsFalse IsNot IsTrue
Join Key Let Lib Like
Long Loop Me Mid Mod
Module MustInherit MustOverride MyBase MyClass
Namespace Narrowing New Next Not
Nothing NotInheritable NotOverridable Object Of
Off On Operator Option Optional
Or Order By OrElse Overloads Overridable
Overrides ParamArray Partial Preserve Private
Property Protected Public RaiseEvent ReadOnly
ReDim REM RemoveHandler Resume Return
SByte Select Set Shadows Shared
Short Single Skip Skip While Static
Step Stop Strict String Structure
Sub SyncLock Take Take While Text
Then Throw To True Try
TryCast TypeOf UInteger ULong Unicode
UShort Until Using Variant  
Went When Where While Widening
With WithEvents WriteOnly Xor  

Although you must always avoid using keywords as names of your variables in your program, if you insist on using one of these keywords to name something, put the word between square brackets. An example would be [True]

The Visual Basic language is not case sensitive. This means that NAME, name, and Name represent the same word. This means that, in the same section (normally called scope), you cannot have two variables with the same name that differ only by their cases. This would cause a name conflict. If you declare a variable in a scope and use it later with a different case, as long as the same characters are used on both names, the Visual Basic compiler would know what variable you are referring to and there would not be any conflict.

Option Explicit

You should always make sure that you declare a variable before using it. Otherwise you may use two variables that seem to be different but because of a mistype, you would think that you are using two variables. Examples are Type and Tape.

To indicate to the compiler that each variable must be declared prior to being used, in the top section of your source file, you should type:

Option Explicit On

Values Fundamentals

 

Introduction

Besides the name, the second piece of information the compiler needs is the amount, also called size, of memory that the variable would need. This is because different values use different amounts of space. For example, the title of a book certainly needs more space than the number of pages of a daily newspaper.

The amount of space that a variable can occupy is referred to as its data type. To limit the amount of gymnastics to perform, the compiler uses categories of data types. For example, it can decide that a simple number would use one small "box" to store its value. On the other hand, it may decide that it would need ten "buckets" to store the title of a movie.

When you create a program, you can let the compiler know the amount of memory you would need for a particular variable. You can do this by specifying the most appropriate category. After telling the compiler that this particular variable would be used to store a number, you can change it in the middle of the program and decide to store an employee's maiden name. On the other hand, some numbers will require more space than others. For example, imagine you want to store the population of countries in a variable. In this case you would request memory that can hold a large number. This type of variable must be able to hold the population of China as well as the population of Burundi. Of course, this same space can hold the number of pages of a daily newspaper. This means that, sometimes, there will appear to be waste of memory. Nowadays, you should not be too concerned with memory as it is becoming less expensive: it is better to have a few empty "buckets" in the computer memory than to have unavailable memory.

To reduce the number of mistakes that could be due to a possible wrong value being stored in a variable, the Visual Basic compiler uses two mechanisms: variable initialization and conversion.

Practical LearningPractical Learning: Introducing Variables

  1. Start Microsoft Visual Basic (either Microsoft Visual Studio or Microsoft Visual Basic 2010 Express)
  2. To create a new application, on the main menu, click File -> New Project
  3. In the middle list, click Console Application
  4. Set the Name to YNB1 (which stands for Yugo National Bank 1)
  5. Click OK
  6. In the Solution Explorer, right-click Module1.vb and click Rename
  7. Type the new name as Training.vb and press Enter
  8. On the main menu, click Project -> YNB1 Properties
  9. Click the arrow of the Application Type box and select Windows Forms Application
  10. Click the Close button Close to close the Property Pages window

A Review of Variable Declaration

We saw that, to declare a variable, you use the Dim keyword, followed by a name. Here is an example:

Module Exercise

    Sub Main()
        Dim Something

    End Sub

End Module

After declaring a variable like this, the compiler reserves a portion of the computer memory for that variable but there may be two possible (small) problems: the compiler does not know how much space that variable would need to store its values and, because of this, the compiler would leave empty that area of memory.

To access the value of a variable, you can simply refer to its name. For example, you can display it to the user. We saw that you could use the MsgBox procedure to display a value. Here is an example:

Module Exercise

    Sub Main()
        Dim Something

        Something = 25
        MsgBox(Something)
    End Sub

End Module

Practical LearningPractical Learning: Declaring Variables

Value Conversion

We mentioned that you could declare a variable but not specify the type of value that would be stored in the memory area reserved for it. When you have declared a variable, the compiler gives it an initial value. This is referred to as initializing the variable. Instead of the compiler doing it, you too can initialize a variable. Initialization partially solves the two problems we mentioned.

In reality, when you declare a variable, the compiler primarily considers it a string and reserves enough space to store any amount of characters. One way you can solve this confusion is to initialize the variable.

To initialize a variable, type its name, followed by =, and followed by the desired value. Here is an example:

Module Exercise

    Sub Main()
        Dim Something

        Something = 25
    End Sub

End Module

After initializing the variable, the new value is stored in its reserved area of memory. When you initialize a variable, the compiler uses the given value to convert it to the appropriate type. For example, if you consider a variable with 25, it becomes considered an integral variable; that is, a variable whose memory can hold natural numbers.

We mentioned that, after declaring a variable, you could change its value whenever you judge it necessary. After declaring a variable as done in the above example, you can assign it any value of you choice. Here are examples:

Module Exercise

    Sub Main()
        Dim Something

        Something = 25
        MsgBox(Something)

        Something = "Manchester United Football Club"
        MsgBox(Something)

        Something = 237565.408
        MsgBox(Something)
    End Sub

End Module

This is one of the unique features that make the Visual Basic (2005) language so flexible.

Requesting a Value

While many programs are meant to simply present values to the user, most applications are used to request values from the user. To make this possible and easy, Visual Basic provides a procedure called InputBox. To use it, type it, followed by parentheses. In its parentheses, enter a sentence that will serve as a guide to the user. The sentence itself should be included between double-quotes.

A typical sentence would indicate what value (or what type of value) you want the user to enter. Here is an example:

InputBox("Enter your first name: ")

The input box appears as a message box with the addition of a text box that would receive the user's value. Here is an example:

Input Box

The user is expected to type a value in the text box. As mentioned for the variables, the value the user types is primarily considered a regular series of characters. To use that series, you must convert it to the appropriate type. We will review the procedures used to convert the values.

The InputBox() procedure provides more details. We will come back to it in Lesson 7.

Visual Basic Operations

 

Introduction

An operation is an action performed on one or more values either to modify one value or to produce a new value by combining existing values. Therefore, an operation is performed using at least one symbol and one value. The symbol used in an operation is called an operator. A variable or a value involved in an operation is called an operand.

A unary operator is an operator that performs its operation on only one operand.

An operator is referred to as binary if it operates on two operands.

The Line Continuation Operator: _

If you plan to write a long piece of code, to make it easier to read, you may need to divide it in various lines. You can do it as you would in any text editor. Here is an example:

Module Exercise

    Sub Main()
        Dim Something

        Something =
            "Manchester United Football Club"
        MsgBox(Something)
    End Sub

End Module

Notice that the variable Something and Manchester ... are written on different lines. As an alternative, you can use the line continuation operator represented by a white space followed by an underscore and an empty space. Here is an example:

Module Exercise

    Sub Main()
        Dim Something

        Something = _
            "Manchester United Football Club"
        MsgBox(Something)
    End Sub

End Module

The Parentheses: ()

Parentheses are used in two main circumstances: in a procedure as we have used Main, MsgBox and InputBox so far, or in an operation. The parentheses in an operation help to create sections in an operation. This regularly occurs when more than one operators are used in an operation. Consider the following operation:

8 + 3 * 5

The result of this operation depends on whether you want to add 8 to 3 then multiply the result by 5 or you want to multiply 3 by 5 and then add the result to 8. Parentheses allow you to specify which operation should be performed first in a multi-operator operation. In our example, if you want to add 8 to 3 first and use the result to multiply it by 5, you would write (8 + 3) * 5. This would produce 55. On the other hand, if you want to multiply 3 by 5 first then add the result to 8, you would write 8 + (3 * 5). This would produce 23.

As you can see, results are different when parentheses are used on an operation that involves various operators. This concept is based on a theory called operator precedence. This theory manages which operation would execute before which one; but parentheses allow you to completely control the sequence of these operations.

The Comma ,

The comma is used to separate variables used in a group. For example, a comma can be used to delimit the names of variables that are declared on the same line. Here is an example:

Module Exercise

    Sub Main()
        Dim CustomerName, AccountNumber, InitialDeposit
        Dim RegularDeposit, TotalDeposits
    End Sub

End Module

The comma can also be used to separate the member of an enumeration or the arguments of a method. We will review all of them when the time comes.

The Assignment Operator =

The assignment operation is used to make a copy of a value or the value of a variable and give the copy to another variable. The assignment operation is performed with the = sign.

After you have declared a variable, before using it, it must have a value. One way you can give a value to a variable is to assign one.

The Double Quotes: ""

A double-quote is used to delimit a group of characters and symbols. To specify this delimitation, the double-quote is always used in combination with another double-quote, as in "". What ever is inside the double-quotes is the thing that need to be delimited. The value inside the double-quotes is called a string. Here is an example:

Sub Main()
    Dim Country

    Country = "Grande Bretagne"
End Sub

If a procedure expects a string, you can type that string in the parentheses of the procedure, we will be using the MsgBox and InputBox procedures.

Practical LearningPractical Learning: Requesting Some Values

  1. To use double-quotes and request some values, change the file as follows:
    Module Training
    
        Sub Main()
            Dim CustomerName
            Dim AccountNumber
            Dim InitialDeposit
    
            CustomerName = InputBox("Enter Customer Name:")
            AccountNumber = InputBox("Enter Customer Acnt #:")
            InitialDeposit = InputBox("Enter Initial Deposit:")
    
            MsgBox("Yugo National Bank")
            MsgBox(CustomerName)
            MsgBox(AccountNumber)
            MsgBox(InitialDeposit)
        End Sub
    
    End Module
  2. To test the program, on the main menu, click Debug -> Start Debugging
  3. Enter the requested value as:
     
    Enter Customer Name: Gertrude Monay
    Enter Customer Acnt #: 92-37293-30
    Enter Initial Deposit: 450.00
  4. When you have finished, return to your programming environment

The Colon Operator :

Most of the time, to make various statements easier to read, you write each on its own line. The Visual Basic language allows you to write as many statements as necessary on the same line. To do this, the statements can be separated by a colon. Here is an example:

Module Exercise

    Sub Main()
        Dim CustomerName
        Dim AccountNumber
        Dim InitialDeposit

        CustomerName = InputBox("Enter Customer Name:")
        AccountNumber = InputBox("Enter Customer Acnt #:")
        InitialDeposit = InputBox("Enter Initial Deposit:")

        MsgBox("Yugo National Bank") : MsgBox(CustomerName)
        MsgBox(AccountNumber) : MsgBox(InitialDeposit)
    End Sub

End Module

String Concatenation: &

The & operator is used to append two strings or expressions. This is considered as concatenating them. For example, it could allow you to concatenate a first name and a last name, producing a full name. The general syntax of the concatenation operator is:

Value1 & Value2

To display a concatenated expression, use the assignment operator on the field. To assign a concatenated expression to a variable, use the assignment operator the same way:

Sub Main()
    Dim FirstName
    Dim LastName 
    Dim FullName 
    
    FirstName = "Francis "
    LastName = "Pottelson"
    FullName = FirstName & LastName
End Sub

To concatenate more than two expressions, you can use as many & operators between any two strings or expressions as necessary. After concatenating the expressions or values, you can assign the result to another variable or expression using the assignment operator.

Practical LearningPractical Learning: Concatenating Some Strings

  1. To use the string concatenator, change the file as follows:
    Module Training
    
        Sub Main()
            Dim CustomerName
            Dim AccountNumber
            Dim InitialDeposit
    
            CustomerName = InputBox("Enter Customer Name:")
            AccountNumber = InputBox("Enter Customer Acnt #:")
            InitialDeposit = InputBox("Enter Initial Deposit:")
    
            MsgBox("Yugo National Bank")
            MsgBox("Customer Name: " & CustomerName)
            MsgBox("Account Number: " & AccountNumber)
            MsgBox("Initial Deposit: $" & InitialDeposit)
        End Sub
    
    End Module
  2. To test the program, on the main menu, click Debug -> Start Debugging
  3. Enter the requested value and, when you have finished, return to your programming environment

Tabs and Carriage Return

Carriage Return-Line Feed

If you are displaying a string but judge it too long, you can segment it in appropriate sections as you see fit. To do this, you can use vbCrLf.

Practical LearningPractical Learning: Using Carriage Return-Line Feed

  1. To use the Carriage Return-Line Feed, change the file as follows:
    Module Training
    
        Sub Main()
            Dim CustomerName
            Dim AccountNumber
            Dim InitialDeposit
            Dim Result
    
            CustomerName = InputBox("Enter Customer Name:")
            AccountNumber = InputBox("Enter Customer Acnt #:")
            InitialDeposit = InputBox("Enter Initial Deposit:")
    
            Result = " =-= Yugo National Bank =-=" & vbCrLf & 
                     "Customer Name:    " & CustomerName & vbCrLf & 
                     "Account Number:   " & AccountNumber & vbCrLf & 
                     "Initial Deposit: $" & InitialDeposit
            MsgBox(Result)
        End Sub
    
    End Module
  2. To test the program, on the main menu, click Debug -> Start Debugging
  3. Enter the requested values. Here are examples:
     
    Using Carriage Return-Line Feed
    Using Carriage Return-Line Feed
    Using Carriage Return-Line Feed
     
    Message Box
  4. When you have finished, return to your programming environment

Carriage Return-Line Feed

From your experience with using the computer keyboard, you probably know already that, to create a tab white space, you can press the Tab key. If you want to get the same effect in the results you present to the user, you can use the vbTab operator of the Visual Basic language. Here are examples:

Sub Main()
    Dim FirstName
    Dim LastName
    Dim FullName

    FirstName = "Francis "
    LastName = "Pottelson"
    FullName = LastName & ", " & FirstName

    MsgBox("First Name: " & vbTab & FirstName & vbCrLf & 
           "Last Name: " & vbTab & LastName & vbCrLf & 
           "Full Name: " & vbTab & FullName)
End Sub

This would produce:

Carriage Return-Line Feed

In the same way, you can create as many vbTab combinations as necessary.

Unary Operators

 

Positive Unary Operator: +

Algebra uses a type of ruler to classify numbers. This ruler has a middle position of zero. The numbers on the left side of the 0 are referred to as negative while the numbers on the right side of the rulers are considered positive:

-∞   -6 -5 -4 -3 -2 -1   1 2 3 4 5 6   +∞
   0
-∞   -6 -5 -4 -3 -2 -1   1 2 3 4 5 6   +∞

A value on the right side of 0 is considered positive. To express that a number is positive, you can write a + sign on its left. Examples are +4, +228, +90335. In this case the + symbol is called a unary operator because it acts on only one operand.

The positive unary operator, when used, must be positioned on the left side of its operand, never on the right side.

As a mathematical convention, when a value is positive, you don't need to express it with the + operator. Just writing the number without any symbol signifies that the number is positive. Therefore, the numbers +4, +228, and +90335 can be, and are better, expressed as 4, 228, 90335. Because the value does not display a sign, it is referred as unsigned.

The Negative Operator -

As you can see on the above ruler, in order to express any number on the left side of 0, it must be appended with a sign, namely the - symbol. Examples are -12, -448, -32706. A value accompanied by - is referred to as negative.

The - sign must be typed on the left side of the number it is used to negate.

Remember that if a number does not have a sign, it is considered positive. Therefore, whenever a number is negative, it MUST have a - sign. In the same way, if you want to change a value from positive to negative, you can just add a - sign to its left.

Arithmetic Operators

 

Addition +

The addition is performed with the + sign. It is used to add one value to another.
To add two numbers, such as 225 and 64, you could use 225 + 64. The result would be 289. The addition is also used to add the values of two variables as in MondayHours + TuesdayHours to get a total number of hours worked on Monday and Tuesday.

Besides arithmetic operations, the + symbol can also be used to concatenate strings, that is, to add one string to another. This is done by appending one string at the end of another. Here is an example:

Module Exercise
    Sub Main()
        Dim FirstName
	Dim LastName 
        Dim FullName

        FirstName = "James "
        LastName  = "Fame"
        FullName  = FirstName + LastName

        MsgBox("Full Name: " & FullName)
    End Sub
End Module

Practical LearningPractical Learning: Using the Addition Operator

  1. To use the addition, change the file as follows:
    Module Training
    
        Sub Main()
            Dim CustomerName
            Dim AccountNumber
            Dim InitialDeposit
            Dim RegularDeposit
            Dim TotalDeposits
            Dim Result
    
            CustomerName = "Paul Bertrand Yamaguchi"
            AccountNumber = "52-92074-95"
            InitialDeposit = 325
            RegularDeposit = 750
            TotalDeposits = InitialDeposit + RegularDeposit
    
            Result = " =-= Yugo National Bank =-=" & vbCrLf & 
                     "Customer Name:   " & CustomerName & vbCrLf & 
                     "Account Number:  " & AccountNumber & vbCrLf & 
                     "Total Deposits: $" & (InitialDeposit + RegularDeposit)
    
            MsgBox(Result)
        End Sub
    
    End Module
  2. To execute the application, press F5
  3. After using the program, return to your programming environment

Multiplication *

The multiplication operation allows you to add a number to itself a certain number of times set by another number. The multiplication operation is performed using the * sign. For example, to add 25 to itself 3 times, you would perform the operation as 25 * 3

Subtraction -

The subtraction operation is performed using the - sign. This operation produces the difference of two or more numbers. It could also be used to display a number as a negative value. To subtract 28 from 65, you express this with 65-28.

The subtraction can also be used to subtract the values of two values.

Practical LearningPractical Learning: Using the Subtraction Operator

  1. To subtract, change the file as follows:
    Module Training
    
        Sub Main()
            Dim CustomerName, AccountNumber
            Dim InitialDeposit, Withdrawals
            Dim RegularDeposit, TotalDeposits
            Dim CurrentBalance
            Dim Result
    
            CustomerName = "Henriette Jolana"
            AccountNumber = "84-48662-72"
            InitialDeposit = 1500
            RegularDeposit = 468.75
            TotalDeposits = InitialDeposit + RegularDeposit
            Withdrawals = 300
            CurrentBalance = TotalDeposits - Withdrawals
    
            Result = " =-= Yugo National Bank =-=" & vbCrLf &
                     "Customer Name:   " & CustomerName & vbCrLf &
                     "Account Number:  " & AccountNumber & vbCrLf &
                     "Total Deposits: $" & (InitialDeposit + RegularDeposit) &
    		 vbCrLf &
                     "Withdrawals:    $" & Withdrawals & vbCrLf &
                     "Current Balance: $" & CurrentBalance
    
            MsgBox(Result)
        End Sub
    
    End Module
  2. To execute the program, press F5
     
    Variables
  3. Return to your programming environment

Integer Division \

Dividing an item means cutting it in pieces or fractions of a set value. Therefore, the division is used to get the fraction of one number in terms of another. Microsoft Visual Basic provides two types of operations for the division. If you want the result of the operation to be a natural number, called an integer, use the backlash operator "\" as the divisor. The formula to use is:

Value1 \ Value2

This operation can be performed on two types of valid numbers, with or without decimal parts. After the operation, the result would be a natural number.

Decimal Division /

The second type of division results in a decimal number. It is performed with the forward slash "/". Its formula is:

Value1 / Value2

After the operation is performed, the result is a decimal number.

Exponentiation ^

Exponentiation is the ability to raise a number to the power of another number. This operation is performed using the ^ operator (Shift + 6). It uses the following formula:

yx

In Microsoft Visual Basic, this formula is written as:

y^x

and means the same thing. Either or both y and x can be values, variables, or expressions, but they must carry valid values that can be evaluated. When the operation is performed, the value of y is raised to the power of x.

Remainder: Mod

The division operation gives a result of a number with or without decimal values, which is fine in some circumstances. Sometimes you will want to get the value remaining after a division renders a natural result.

The remainder operation is performed with keyword Mod. Its formula is:

Value1 Mod Value2

The result of the operation can be used as you see fit or you can display it in a control or be involved in another operation or expression.

Bit Operations

 

Introduction

From our introduction to variables, you may remember that the computer stores its data in memory using small locations that look like boxes and each box contains a bit of information. Because a bit can be represented only either as 1 or 0, we can say that each box contains 1 or 0. Bit manipulation consists of changing the value (1 or 0, or 0 or 1) in a box. As we will see in the next few operations, it is not just about changing a value. It can involve reversing a value or kind of "moving" a box from its current position to the next position.

The operations on bits are performed on 1s and 0s only. This means that any number is decimal or hexadecimal format involved in a bit operation must be converted to binary first.

You will almost never perform some of the operations we are going to review. You will hardly perform some other operations. There is only one operation you will perform on a regular basis. The OR operation is very regular in Microsoft Windows (Win32) programming so much that we were obliged to include this whole section in the lesson, as opposed to mentioning only OR.

"Reversing" a Bit

Remember that, at any time, a box (or chunk) in memory contains either 1 or 0:

Bits

Bit reversal consists of reversing the value of a bit. If the box contains 1, you can reverse it to 0. If it contains 0, you can reverse it to 1. To support this operation, the Visual Basic language provides the Not Operator.

As an example, consider the number 286. The decimal number 286 converted to binary is 100011110. You can reverse each bit as follows:

286 1 0 0 0 1 1 1 1 0
Not 286 0 1 1 1 0 0 0 0 1
 

Bitwise Conjunction

Bitwise conjunction consists of adding the content of one box (a bit) to the content of another box (a bit). To support the bitwise conjunction operation, the Visual Basic language provides the And operator.

To perform the bit addition on two numbers, remember that they must be converted to binary first. Then:

As an example, consider the number 286 bit-added to 475. The decimal number 286 converted to binary is 100011110. The decimal number 4075 converted to binary is 111111101011. Based on the above 4 points, we can add these two numbers as follows:

286 0 0 0 1 0 0 0 1 1 1 1 0
4075 1 1 1 1 1 1 1 0 1 0 1 1
286 And 4075 0 0 0 1 0 0 0 0 1 0 1 0

Therefore, 286 And 4075 produces 100001010 which is equivalent to:

  Bit8 Bit7 Bit6 Bit5 Bit4 Bit3 Bit2 Bit1 Bit0
  256 128 64 32 16 8 4 2 1
286 And 4075 1 0 0 0 0 1 0 1 0
  256 0 0 0 0 8 0 2 0

This means that 286 And 4075 = 256 + 16 + 2 = 266

This can also be programmatically calculated as follows:

Module Exercise

    Sub Main()
        Dim Number1 = 286
        Dim Number2 = 4075
        Dim Result = Number1 And Number2

        MsgBox("286 And 4075 = " & (Result))
    End Sub

End Module

This would produce:

And

Bitwise Disjunction

Bitwise disjunction consists of disjoining one a bit from another bit. To support this operation, the Visual Basic language provides the Or operator.

To perform a bitwise conjunction on two numbers, remember that they must be converted to binary first. Then:

As an example, consider the number 305 bit-disjoined to 2853. The decimal number 305 converted to binary is 100110001. The decimal number 2853 converted to binary is 101100100101. Based on the above 4 points, we can disjoin these two numbers as follows:

305 0 0 0 1 0 0 1 1 0 0 0 1
2853 1 0 1 1 0 0 1 0 0 1 0 1
305 Or 2853 1 0 1 1 0 0 1 1 0 1 0 1

Therefore, 305 Or 2853 produces 101100110101 which is equivalent to:

  Bit11 Bit10 Bit9 Bit8 Bit7 Bit6 Bit5 Bit4 Bit3 Bit2 Bit1 Bit0
  2048 1024 512 256 128 64 32 16 8 4 2 1
305 Or 2853 1 0 1 1 0 0 1 1 0 1 0 1
  2048 0 512 256 0 0 32 16 0 4 0 1

This means that 286 And 4075 = 2048 + 512 + 256 + 32 + 16 + 4 + 1 = 2869

This can also be programmatically calculated as follows:

Module Exercise

    Sub Main()
        Dim Number1 = 305
        Dim Number2 = 2853
        Dim Result = Number1 Or Number2

        MsgBox("286 Or 4075 = " & (Result))
    End Sub

End Module

This would produce:

Or

Bitwise Exclusion

Bitwise exclusion consists of adding two bits with the following rules. To support bitwise exclusion, the Visual Basic language provides an operator named Xor:

As an example, consider the number 618 bit-excluded from 2548. The decimal number 618 converted to binary is 1001101010. The decimal number 2548 converted to binary is 100111110100. Based on the above 2 points, we can bit-exclude these two numbers as follows:

618 0 0 1 0 0 1 1 0 1 0 1 0
2548 1 0 0 1 1 1 1 1 0 1 0 0
618 Xor 2548 1 0 1 1 1 0 0 1 1 1 1 0

Therefore, 305 Or 2853 produces 101110011110 which is equivalent to:

  Bit11 Bit10 Bit9 Bit8 Bit7 Bit6 Bit5 Bit4 Bit3 Bit2 Bit1 Bit0
  2048 1024 512 256 128 64 32 16 8 4 2 1
618 Xor 2548 1 0 1 1 1 0 0 1 1 1 1 0
  2048 0 512 256 128 0 0 16 8 4 2 0

This means that 286 And 4075 = 2048 + 512 + 256 + 128 + 16 + 8 + 4 + 2 = 2974

This can also be programmatically calculated as follows:

Module Exercise

    Sub Main()
        Dim Number1 = 618
        Dim Number2 = 2548
        Dim Result = Number1 Xor Number2

        MsgBox("286 Xor 4075 = " & (Result))
    End Sub

End Module

This would produce:

Xor

Left-Shifting the Bits

Left shifting the bits consists of pushing each bit from right to left. You can do this by one ore more bits. Once again, to perform this operation, the number has to be converted to its binary equivalent. To support this operation, the Visual Basic language provides an operator represented as <<.

Imagine you have a number as 741. Its binary equivalent is 1011100101 and can be represented as:

1 0 1 1 1 0 0 1 0 1

To perform a left shift operation on these bits, you push each from its position to the left, depending on the number of pushes you want. For example, to left-shift by 1 bit, you push each bit to the left by one position. Actually, you consider the bit at position x and the bit to its left at position y. You replace the value of Bit y by the value of Bit x. If Bit x is the most right bit, it receives a value of 0. This can be illustrated as follows:

Original   1 0 1 1 1 0 0 1 0 1
<< by 1 1 0 1 1 1 0 0 1 0 1 0

As a result, we get 10111001010. The decimal result can be calculated as follows:

  Bit10 Bit9 Bit8 Bit7 Bit6 Bit5 Bit4 Bit3 Bit2 Bit1 Bit0
  1024 512 256 128 64 32 16 8 4 2 1
741 << 1 1 0 1 1 1 0 0 1 0 1 0
  1024 0 256 128 64 0 0 8 0 2 0

Consequently, 741 << 1 = 1024 + 256 + 128 + 64 + 8 + 2 = 458

This can also be evaluated programmatically as follows:

Module Exercise

    Sub Main()
        MsgBox("741 << 1 = " & (741 << 1))
    End Sub

End Module

This would produce:

Left Shift

In the same way, you can push the bits to the left by more than one unit.

Right-Shifting the Bits

You can shift the bits to the right. Everything is done as reviewed for the left shift but in reverse order. To support this operation, the Visual Basic language provides the >> operator.

ApplicationApplication: Ending the Lesson

  1. On the main menu, click File -> Close Solution (Microsoft Visual Studio) or File -> Close Project (Microsoft Visual Basic 2010 Express)
  2. When asked whether you want to save, click Discard
 

Previous Copyright © 2008-2024, FunctionX, Inc. Monday 14 February 2016 Next