3

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

例如,如果我想添加“苹果”的二进制表示,它会写入文件 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()

非常感谢...

4

1 回答 1

1

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

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 用于您的“苹果”

如果你将它保存为 char 或 byte 我会认为它使用了 5 个字节和 1k 长如果你将它保存为整数我会认为它使用了 10 个字节和 1k 长

参考:http: //msdn.microsoft.com/en-us/library/system.io.binarywriter.aspx

于 2013-04-08T01:09:20.530 回答