在VB.Net中将位写入二进制文件

3

我需要创建一个包含二进制输入的文件,但是当我这样做时,它会按字节而不是位处理。

例如,如果我想添加“apple”的二进制表示, 它会写入文件0110000101110000011100000110110001100101,其中包含40位。 然而,当我查看文件时,它显示40个字节,因为它将每个位作为字符,并以字节方式保存。 如何在VB.net中防止这种情况发生并以位方式保存所有信息?

Dim fs As New FileStream("\binfile.bin", FileMode.Append)
    Dim bw As New BinaryWriter(fs)
    Dim TempStr As String

    For t As Integer = 0 To Nameoftable.Length - 1
        Dim bin As String = _
            LongToBinary(Asc(Nameoftable.Substring(t, 1))) 'BIT CONVERTER FUNCTION
        TempStr &= bin.Substring(bin.Length - 8)
    Next t

        bw.Write(TempStr)

    bw.Close()

非常感谢...


不要使用LongToBinary()。不清楚你为什么要这样做。如果你想要字节,那么StreamWriter就可以很好地工作。 - Hans Passant
我使用LongToBinary函数,因为我需要将数据保存为二进制格式,因为在记录的某些部分中,我使用哈希和位运算。例如,我需要数据的第一个位状态,然后在其余数据中使用位记录。实际问题是,即使我将所有字符串和整数更改为二进制格式,它们仍会以字符形式写入.bin文件。我该如何防止这种情况发生? - Palindrom
此外,我刚刚尝试了StreamWriter,对于我的情况来说几乎与BinaryWriter相同。我需要按位写入。例如,如果我将5个位添加到二进制文件中,则它必须增加5个位而不是5个字节。 - Palindrom
1个回答

1

您必须使用二进制读写对象,并指定发送到写入流的数据的字段类型,对于从流中读取的数据,读取器也是如此。

Dim filename As String = "c:\temp\binfile.bin"
Dim writer As BinaryWriter
Dim reader As BinaryReader
Dim tmpStringData As String
Dim tmpByteData As Byte
Dim tmpCharData As Char
Dim tempIntData as Integer
Dim tempBoolData as Boolean
'
writer = New BinaryWriter(File.Open(filename, FileMode.Append))
Using writer
  writer.Write("apple")
  'writer.Write(YourByteDataHere)   'byte
  'writer.Write(YourCharHere)   'char
  'writer.Write(1.31459)        'single
  'writer.Write(100)        'integer
  'writer.Write(False)        'boolean
End Using
writer.Close()
'
If (File.Exists(filename)) Then
  reader = New BinaryReader(File.Open(filename, FileMode.Open))
  Using reader
    tmpStringData = reader.ReadString()
    'tempByteData = reader.ReadByte()
    'tempCharData = reader.ReadChar()
    'tempSingleData = reader.ReadSingle()
    'tempIntData = reader.ReadInt32()
    'tempBoolData = reader.ReadBoolean()
  End Using
  reader.Close()
End If

我使用了ReadString()方法来写入字符串"apple" 如果您愿意,可以使用字符或字节的chr代码,这种情况下,您必须根据将其发送到流中的方式(作为字节,字符或整数)使用ReadByte()或ReadChar()或ReadInt() 因此,文件大小为6个字节,其中1个字节用于文件流处理程序自己的内部使用,另外5个字节用于您的“apple” 如果您将其保存为字符或字节,则我认为它使用了5个字节并且长达1k 如果您将其保存为整数,则我认为它使用了10个字节并且长达1k 参考链接:http://msdn.microsoft.com/en-us/library/system.io.binarywriter.aspx

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接