I have a custom file format that I need to be able to read and write single bits from. I know the positions of these bits and can read them by:
dim fileName as string 'path to the file
dim fil as integer 'holds the first available file number
dim x as byte
fil = FreeFile
open fileName for Binary as #fil
get #fil, 55,x 'the first bit is located in byte 55 and is the third bit
close fil
'after retrieving the byte, I have a conversion routine that converts the byte to a bit string. The function ByteToBit converts a byte a bit string.
'------------------------
Private Function ByteToBit(ByteArray) As String
Dim i As Integer
ByteToBit = ""
For i = 7 To 0 Step -1
If Int(ByteArray / (2 ^ i)) = 1 Then
ByteToBit = ByteToBit & "1"
ByteArray = ByteArray - (2 ^ i)
Else
If ByteToBit <> "" Then
ByteToBit = ByteToBit & "0"
End If
End If
Next i
End Function
'------------------------
AFter converting the Byte to a bit string I can use the Mid$ function to pull out the specific bit that I need.
First Question, is there an easier way to read a specific bit in a file?
How do I write the specific bit back to the file? For example, if I flip the bit how do I write the changes back?
Are there intrinsic functions in VB that would assist with this or am I reading the bits the best way?
Troy Williams B.Eng.
fenris@hotmail.com
dim fileName as string 'path to the file
dim fil as integer 'holds the first available file number
dim x as byte
fil = FreeFile
open fileName for Binary as #fil
get #fil, 55,x 'the first bit is located in byte 55 and is the third bit
close fil
'after retrieving the byte, I have a conversion routine that converts the byte to a bit string. The function ByteToBit converts a byte a bit string.
'------------------------
Private Function ByteToBit(ByteArray) As String
Dim i As Integer
ByteToBit = ""
For i = 7 To 0 Step -1
If Int(ByteArray / (2 ^ i)) = 1 Then
ByteToBit = ByteToBit & "1"
ByteArray = ByteArray - (2 ^ i)
Else
If ByteToBit <> "" Then
ByteToBit = ByteToBit & "0"
End If
End If
Next i
End Function
'------------------------
AFter converting the Byte to a bit string I can use the Mid$ function to pull out the specific bit that I need.
First Question, is there an easier way to read a specific bit in a file?
How do I write the specific bit back to the file? For example, if I flip the bit how do I write the changes back?
Are there intrinsic functions in VB that would assist with this or am I reading the bits the best way?
Troy Williams B.Eng.
fenris@hotmail.com