PDA

Click to See Complete Forum and Search --> : HELP ME PLS!!!!!!!!!!!!!!!!!!!!!Student with problem


sqapg
Jul 24th, 2001, 09:00 PM
how to write a 4 bit counter using visual basic. like when i press up, it will change from 0000 to 0001 then up again from 0001 to 0010 so on and so forth. thanks for helping me out its for my school assignment.i am stuck with this. thanks once again. pls email the sample code to sqapg5@yahoo.com

unformed
Jul 25th, 2001, 12:15 PM
s = Format(n, "0000")

that should do it...

nishantp
Jul 25th, 2001, 01:28 PM
No that wont do it. If just makes sure the number returned is 4 digits long, it doesnt count binary.


s = format(n, "0000")

just adds zeroes. Counting binary could be pretty tricky in VB. TRy using C or C++ if you know it...

THEROB
Jul 25th, 2001, 02:20 PM
Here is some code to change decimal to binary:



Public Function CONV(Dec As Long) As String

Dim i As Long, x As Long, bin As String
Const maxpower = 32 ' Maximum number of binary digits supported.
bin = "" 'Build the desired binary number in this string, bin.
x = Dec

If x > 2 ^ maxpower Then
MsgBox "Number must be no larger than " & Str$(2 ^ maxpower)
CONV = ""
Exit Function
End If

' Here is the heart of the conversion from decimal to binary:

' Negative numbers have "1" in the 32nd left-most digit:
If x < 0 Then bin = bin + "1" Else bin = bin + "0"

For i = maxpower To 0 Step -1
If x And (2 ^ i) Then ' Use the logical "AND" operator.
bin = bin + "1"
Else
bin = bin + "0"
End If
Next
CONV = bin ' The bin string contains the binary number.

End Function


So you can just store the number as decimal and just convert it to binary.

Rob

unformed
Jul 25th, 2001, 02:25 PM
oh yeah, sorry about that....

i read it as he wanted it to be four digits....

kedaman
Jul 25th, 2001, 03:24 PM
Private Sub Command1_Click()
Static x&, a(7) As Byte
x = x + 1
a(0) = 48 - CBool(x And 8)
a(2) = 48 - CBool(x And 4)
a(4) = 48 - CBool(x And 2)
a(6) = 48 - CBool(x And 1)
Caption = CStr(a)
End Sub

Nucleus
Aug 9th, 2001, 09:52 PM
Here is a different approach:


Private Sub Command1_Click()
Static x

x = x + 1
Debug.Print Format$(bin(x), "0000")

End Sub

Function bin(ByVal x As Long) As String
Do
bin = (x And 1) & bin
x = x \ 2
Loop While x
End Function