-
Jul 3rd, 2008, 03:21 AM
#1
Thread Starter
Junior Member
how to access bit in a byte
hi friends,
i had declared port_data as a variable of byte data type . how to access a particular bit in a byte. how to display binary form of decimal number.
for example port_data = 255; binary form is 1111 1111.
port_data = 10; binary form is 0000 1001.
-
Jul 3rd, 2008, 08:12 AM
#2
Re: how to access bit in a byte
Here's one way of doing it.
Code:
Public Function ByteToBin(ByVal num As Byte) As String
Dim sRetVal As String
Dim i As Integer
sRetVal = "00000000"
For i = 0 To 7
If (num And (2 ^ i)) <> 0 Then
Mid(sRetVal, 8 - i) = "1"
End If
Next
ByteToBin = Left$(sRetVal, 4) & " " & Right$(sRetVal, 4)
End Function
-
Jul 3rd, 2008, 10:33 AM
#3
Thread Starter
Junior Member
Re: how to access bit in a byte
thanks it works fine but how to access ( means to modify ) a particular bit in a byte variable.
-
Jul 3rd, 2008, 02:20 PM
#4
Re: how to access bit in a byte
In a byte the least significant bit has the value 1 and the most significant bit has the value 128, right? The others all all powers of two. So if you want to set or remove the least significant bit you would do this:
Code:
newByte = currentByte Or 1 '<- Sets the least significant bit to 1 (or leave it if it's set already)
newByte = currentByte Xor 1 '<- Toggle the least significant bit (set it to 1 if it is 0, and the other way around)
newByte = currentByte And Not 1 '<- Sets the least significant bit to 0.
To set any other bit but the least significant just change the value 1 to 2, 4, 8, 16, 32, 64, or 128.
-
Jul 4th, 2008, 01:47 AM
#5
Thread Starter
Junior Member
Re: how to access bit in a byte
thanks a lot sir. it works fine.
-
Jul 4th, 2008, 11:36 AM
#6
Hyperactive Member
Re: how to access bit in a byte
i wrote this for you to give you a better look into how to modify a bit from a byte. you can change the parameters to modify larger numbers as well.
Code:
Option Explicit
Private Enum bState
[Off] = 0
[On] = 1
[Toggle] = 3
End Enum
Private Sub Form_Load()
Dim MyByte As Byte
MyByte = 128 'our example value
MyByte = ModifyBit(MyByte, 7, bState.Toggle)
MsgBox MyByte
End Sub
'Inputs The Value, The Bit Number, The Method you wish to use to modify
Private Function ModifyBit(ByVal pNumber As Byte, ByVal bitNum As Byte, Optional ByVal State As bState = Toggle) As Byte
Select Case State
Case bState.On
ModifyBit = pNumber Or (2 ^ bitNum)
Case bState.Off
ModifyBit = pNumber And Not (2 ^ bitNum)
Case bState.Toggle
ModifyBit = pNumber Xor (2 ^ bitNum)
End Select
End Function
-
Jul 4th, 2008, 01:22 PM
#7
Thread Starter
Junior Member
Re: how to access bit in a byte
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|