< back to < home page < Programming

Coverting binary literals to numbers and back

How do you convert a number to a binary literal in Visual Basic .net?
How do you convert a binary literal to a number in Visual Basic .net?
A suggested answer is given in the following simple windows form program. This page has 4 sections:

What the program does

This program will convert a number from 0 - 255 into a text representation of the binary equivalent (a binary literal). For example, entering 134 will produce 10000110. The program will also convert a binary literal to its equivalent decimal number. If you enter 11111101 it will display 253.

The functions that do the conversion are:
bitsToByte - takes a binary literal eg. 11111111 and converts it to a number eg. 255
byteToBits. - takes a number eg. 170 and converts it to a binary literal eg. 10101010
The rest of the code simply validates what the user enters as being a valid number or valid binary literal. There are two versions of the code presented. The first contains extensive comments that hopefully explain what is going on and how the code works. The second version is the same except the comments have been removed for brevity.

Bytes and bits program

To build the program you can use Microsoft Visual Basic Express (free) or Micorsoft Visual Studio. Any recent version (2005 - 2008) should work.

1) Create a form with the following controls:

Bytes and Bits image

  Control Text
1 TextBox1
2 TextBox2
3 TextBox3
4 TextBox4
5 Button1 Convert to binary literal
6 Button2 Convert binary liteal to byte
7 Button3 Close
8 Lable1 Number to convert
9 Label2 Literal to convert

Feel free to change the text of the labels and buttons to whatever you want. As you create the controls it can be a good idea to give the controls more meaningful names. If you do this remember to changes the control names in the code.

2) Add the following code to the form. Simply copy and paste it from below.

The first version of the code is heavily commented below is a version without the comments

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'When user clicks Button1 - Convert to binary literal 'Variable to hold text entered converted to integer Dim myNumber As Integer 'Variable to hold integer converted to byte Dim myByte As Byte 'Check if the text string entered equates to a number 'and can be converted to an integer If IsNumeric(TextBox1.Text) Then ' It does...convert the string to an integer ' and assign it to the myNumber variable myNumber = CInt(TextBox1.Text) Else ' It doen't... ' warn user, clear textbox, ' set focus to text box and exit sub MessageBox.Show("Enter a valid number") TextBox1.Text = "" TextBox1.Focus() Exit Sub End If 'Is the number within an acceptable range 'in this case 0 - 255 as we are only 'using 8 bit bytes eg. 11101011 If myNumber >= 0 And myNumber <= 255 Then 'it is within range... 'convert the integer to a byte myByte = CByte(myNumber) Else 'it isn't within range 'warn user, clear textbox, 'set focus to text box and exit sub MessageBox.Show("Enter a number between 0 and 255") TextBox1.Text = "" TextBox1.Focus() Exit Sub End If 'Send the byte to the function 'to convert it to a binary literal 'then display it in TextBox2 TextBox2.Text = byteToBits(myByte) End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click 'When user clicks Button2 - Convert binary literal to byte 'Varialbe to hold binary literal entered Dim binString As String 'Varialbe to hold literal converted to a byte Dim binByte As Byte 'Get the number of characters (length) of text 'entered by user Dim binStringLength As Integer binStringLength = TextBox3.Text.Length 'Check to make sure they have only entered '8 characters If binStringLength <> 8 Then 'less or more than 8 characters 'warn the user and exit the sub MessageBox.Show("You must enter 8 bits") Exit Sub Else '8 charcters only 'binString set to text entered binString = TextBox3.Text 'Check that only 1s (ones) and 0s (zeros) 'have been entered 'loop through each character in string For i As Integer = 0 To 7 'Get single character at position i 'in text Dim testLetter = binString.Substring(i, 1) 'Check if it is a 1 (one) or 0 (zero) If Not (testLetter = "1" Or testLetter = "0") Then 'Not a 1 or 0. Warn user and exit sub MessageBox.Show("You can only enter 1s or 0s") Exit Sub Else 'There were only 1s and 0s so 'Send the string (binary literal eg. 10110011) to 'function to the bitsToByte function to convert it to a byte binByte = bitsToByte(binString) 'Display the result TextBox4.Text = binByte.ToString End If Next End If End Sub
Private Function byteToBits(ByVal byteToConvert As Byte) As String 'Takes a byte and converts it 'to a string of 1s (ones) and 0s (zeros) 'representing the number in binary notation 'Byte variable to hold the shifted bit Dim shiftByte As Byte 'Set to 1 or, more importantly, 00000001 shiftByte = 1 'Byte variable to hold a temporary byte Dim tempByte As Byte tempByte = 0 'String variables to hold working strings Dim testBit As String = "" Dim result As String = "" 'Loop 8 times with i counting 'down from 7 to 0 For i As Integer = 7 To 0 Step -1 'Reset shiftByte to 1 shiftByte = 1 'Each time through the loop 1 is shifted ' i times to the left in shiftByte ' eg. shiftByte is 00000001 ' the bits are shifted by i places ' if i is 3 then shiftByte will be 00001000 ' tempByte becomes shiftByte ANDed with the ' byteToConvert. tempByte = (shiftByte << i) And byteToConvert 'Test if the result of above is 0 (zero) If tempByte = 0 Then 'Will be 0 if there is a 0 'at the same position in the 'byteToConvert where the 1 is currently in the 'shiftByte testBit = "0" Else testBit = "1" End If 'Append the "0" or "1" to build up the result string result = result & testBit Next 'And return it Return result End Function
Private Function bitsToByte(ByVal bitLiteral As String) As Byte 'Takes a number in byte format and 'converts it to a binary string literal 'eg. a number (0-255) to binary literal (10010011) 'would convert 134 to 10000110 'Varible for working byte Dim tempByte As Byte tempByte = 0 'Loop through each character in the binary literal 'if the character is a "0" (zero) add nothing to the 'temporary byte (leave it unchanged) 'If the character is a "1" (one) then a 1 will be 'placed at the same position in the tempByte 'This is what the 'Or' does 'Loop trough each character in the binary literal from 'right to left. 'The equivalent of working from the Least Significant Bit (LSB) 'to the Most Significant Bit (MSB) of the byte For i As Integer = 7 To 0 Step -1 'Long code version showing 'workings' commented out below: '********************************************************* 'Dim bitValue As Integer = 0 'Take the character at postion i in the string 'Convert the text "1" or "0" to an integer 1 or 0 'bitValue = CInt(bits.Substring((i), 1)) ''Invert' the value of the counter i 'We need this to count UP from 0 'So if i is 7 we need the value 0, if i is 0 we need 7 'Dim invert As Integer 'invert = Math.Abs(i - 7) 'Shift whatever is at postion i in the literal 'We will be shifting a 1 if it's a "1" 'and a 0 if it's a "0" 'It will be shifted to the left invert times 'Dim positionByte As Byte 'positionByte = CByte(bitValue) << invert 'OR tempByte with the positionByte 'tempByte = tempByte Or positionByte '********************************************************** 'The line below is the short equivalent of the section 'of commented out code above tempByte = tempByte Or CByte(CInt(bitLiteral.Substring(i, 1)) << Math.Abs(i - 7)) Next 'Return the byte Return tempByte End Function
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click Close() End Sub End Class



Short non-commented version of the code

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim myNumber As Integer Dim myByte As Byte If IsNumeric(TextBox1.Text) Then myNumber = CInt(TextBox1.Text) Else MessageBox.Show("Enter a valid number") TextBox1.Text = "" TextBox1.Focus() Exit Sub End If If myNumber >= 0 And myNumber <= 255 Then myByte = CByte(myNumber) Else MessageBox.Show("Enter a number between 0 and 255") TextBox1.Text = "" TextBox1.Focus() Exit Sub End If TextBox2.Text = byteToBits(myByte) End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Dim binString As String Dim binByte As Byte Dim binStringLength As Integer binStringLength = TextBox3.Text.Length If binStringLength <> 8 Then MessageBox.Show("You must enter 8 bits") Exit Sub Else binString = TextBox3.Text For i As Integer = 0 To 7 Dim testLetter = binString.Substring(i, 1) If Not (testLetter = "1" Or testLetter = "0") Then MessageBox.Show("You can only enter 1s or 0s") Exit Sub Else binByte = bitsToByte(binString) TextBox4.Text = binByte.ToString End If Next End If End Sub
Private Function byteToBits(ByVal byteToConvert As Byte) As String Dim shiftByte As Byte shiftByte = 1 Dim tempByte As Byte tempByte = 0 Dim testBit As String = "" Dim result As String = "" For i As Integer = 7 To 0 Step -1 shiftByte = 1 tempByte = (shiftByte << i) And byteToConvert If tempByte = 0 Then testBit = "0" Else testBit = "1" End If result = result & testBit Next Return result End Function
Private Function bitsToByte(ByVal bitLiteral As String) As Byte Dim tempByte As Byte tempByte = 0 For i As Integer = 7 To 0 Step -1 tempByte = tempByte Or CByte(CInt(bitLiteral.Substring(i, 1)) << Math.Abs(i - 7)) Next Return tempByte End Function
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click Close() End Sub End Class

Top of page

How it works

The two main functions both make use of Visual Basic bitwise operations.

Converting a binary literal to a number

bitsToByte - The user enters a text string made up of eight '1's and '0's. This is the binary literal. The function then works through the string one character at a time taking the character at position i in the string (i is the loop counter). It converts each character into a number - an integer 1 or 0:

CInt(bitLiteral.Substring(i, 1))

it then converts the integer into a Byte variable containing 1 or 0.

CByte(CInt(bitLiteral.Substring(i, 1)) << Math.Abs(i - 7))

that byte (which is 00000000 or 00000001) is then 'bitshifted' by the 'inverse' of the loop counter i. Bitshifting means that all the digits in the byte are moved (or shifted) one place to the left. The code in red above does this.

Lets take the literal 00101101. The function will take the '1' at the far right and convert it to a number 1.

This number 1 is then stored in a variable of type Byte. The byte for 1 contains the bits - 00000001

As the 00000001 is converted to a byte is is 'bitshifted' by Math.Abs(i - 7). First time through the loop the counter is 7 so Math.Abs(7-7) = 0. It is bitshifted by 0 places - it doesn't move this time! The byte still contains 00000001.

The tempByte which is currently 0 is then OR'd with this 00000001

00000000
OR 00000001
= 00000001

The second time through the loop the counter, i, is 6 and its inverse is 1. The function therefore takes the 6th character from the literal 00101101. The 0 produces a byte containing 00000000. This is shifted by 1 place to the left (which makes no difference!) and it is still 00000000. This is then OR'd with the tempByte which is now 00000001.

00000001
OR 00000000
= 00000001

The third time through the loop the counter, i, is 5 and its inverse is 2. The function therefore takes the 5th character of from the literal 00101101. The 1 produces a byte containing 00000001. This is shifted 2 places to the left and is now 00000100. This is then Or'd with the tempByte which is now 00000001

00000001
OR 00000100
= 00000101

The function continues taking each character in turn, converting it to a 1 or 0 and ORing this with the tempByte. In essence it is simply putting a 1 or 0 in the same place in the tempByte as a "1" or "0" appears in the binary literal.

The tempByte in our example ends up being 00101101. But this is exactly what we started off with you might say. Well yes but we started with a string of 8 "1"s or "0"s and have ended up with 8 bits of either 1 or 0. 8 bits of 1 or 0 are a byte. Visual Basic sees bytes as numbers. We can now display the byte as number (in this case 45).

Top of page

Converting a number to a binary literal

byteToBits - The user enters a number between 0 and 255. This number is converted to a byte and stored in byteToConvert. The functions then loops 8 times. The loop counter counts down from 7 to 0.

Each time through the loop the a byte containing the bits 00000001 (the decimal number 1) is bit shifted (moved to the left) by the same value as the loop counter i. This byte is then AND'ed with the byteToConvert and the result stored in tempByte.

tempByte will then either be 00000001 or 00000000. It is 00000001 if the bit at postion i in the byteToConvert is a 1. It is 00000000 if the bit at position i of the byteToConvert is a 0.

Each time through the loop tempByte is tested and if it contains 00000001 a "1" is appended to a text string. If tempByte contains 0000000 a "0" is appended to the text string result.

At the end of the loop a text string of 8 characters is created. It has "1"s and "0"s in the same position as the 1s and 0s in the byte we started with.

For example lets take the number 45. Convert it to a byte and the bits in that byte are: 00101101. This is our byteToConvert. Lets follow it through our function loop:

loop counter i
byteToConvert
00000001
bitshifted by i

bit at position i
in byteToConvert
as text

result
i = 7 00101101 10000000 "0" "0"
i = 6 00101101 01000000 "0" "00"
i = 5 00101101 00100000 "1" "001"
i = 4 00101101 00010000 "0" "0010"
i = 3 00101101 00001000 "1" "00101"
i = 2 00101101 00000100 "1" "001011"
i = 1 00101101 00000010 "0" "0010110"

i = 0

00101101 00000001 "1" "00101101"

result ends up being "00101101". A binary literal of the number 45.

Bit shifting and bitwise operations like AND and OR can at first seem a little complicated. They can, however, be very useful when you wish to manipulte the bits within a byte. To convert between numbers and binary literals or to use the bits as flags.

I created the functions above to help me process numbers and binary literals before sending and receiving them via a serial port to various PIC and Arduino microcontroller projects I'm working on. Being able to convert between numbers and literals is very useful when you want to control the exact 1's and 0's you send.

The program above can be created in Microsoft Visual Basic Express and Microsoft Visual Studio 2005 or 2008.

Top of page

Related links

Bitwise operation - Wikipedia page on Bitwise operations


< back to < home page < Programming

© Andrew Craigie 2009

Please feel free to use this code in your programs for non commercial use only. Please acknowledge any uses.


Creative Commons License
Coverting binary literals to numbers and back
by Andrew Craigie is licensed under a Creative Commons Attribution-Non-Commercial-Share Alike 2.5 UK: Scotland License.
Based on a work at www.acraigie.com.