Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

manipulating bits

Status
Not open for further replies.

fenris

Programmer
May 20, 1999
824
CA
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 <> &quot;&quot; Then
ByteToBit = ByteToBit & &quot;0&quot;
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

 
I'm not sure they are BETTER than what you have 'grown', but bitwise operators exist. To select specific bits, you need to develop the &quot;Masks&quot; for the specific bits. These are 'generally' just a set of hex value constants. To Set / Reset (&quot;Flip&quot;) bits, just XOR the 'variable' with the mask for the bit. In binary files, I believe the Put operation is the 'compliment' of the get operation you are already using, so it is available for the 'replacement' of the value.

MichaelRed
mred@att.net

There is never time to do it right but there is always time to do it over
 
Michael, thanks for the response. It's given me some new directions to look in.
Troy Williams B.Eng.
fenris@hotmail.com

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top