16,554
社区成员
发帖
与我相关
我的任务
分享
Dim fs As New System.IO.FileStream("c:\yx14.dat", IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
Dim br As New System.IO.BinaryReader(fs)
br.BaseStream.Position = 529
Dim dataCount As Integer = 2048 / 4
Dim data(dataCount - 1) As Integer
Dim dataIsLittleEndian As Boolean = True '首先你得约定/判定数据的字节序'
If dataIsLittleEndian <> BitConverter.IsLittleEndian Then
'和系统不一致的时候需要交换'
For i As Integer = 0 To dataCount - 1
Dim byte4() As Byte = br.ReadBytes(4)
Array.Reverse(byte4)
data(i) = BitConverter.ToInt32(byte4, 0)
Next
Else
'一致的时候直接读取'
For i As Integer = 0 To dataCount - 1
data(i) = br.ReadInt32()
Next
End If
br.Close()
fs.Close()
Dim fs As New System.IO.FileStream("c:\yx14.dat", IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
Dim br As New System.IO.BinaryReader(fs)
br.BaseStream.Position = 529
Dim dataCount As Integer = 2048 / 4
Dim data(dataCount - 1) As Integer
For i As Integer = 0 To dataCount - 1
'读入文件数据前判断当前系统的字节序,如果符合低位在前,高位在后直接给数组赋值,否则,把数组翻转'
If BitConverter.IsLittleEndian Then
data(i) = br.ReadInt32() '字节序相同时直接读取数据
Else
'字节序相反时如何读取??
'data(i) = BitConverter.GetBytes(br.ReadInt32())
'Array.Reverse(data(i))
End If
Next
br.Close()
fs.Close()
For i As Integer = 0 To dataCount - 1
ListBox1.Items.Add((data(i)))
Next
现在想在读c:\14.dat数据到DATA()前判断一下机器的字节序,然后再给数组赋值,当字节相反时怎么办,解决不了。。。求指教Module Module1
Sub Main()
Console.Write("Input Value: ")
Dim v As Integer = CInt(Console.ReadLine())
'写入:和当前系统Endian相反的,把数组翻转'
Dim leBytes() As Byte
Dim beBytes() As Byte
If BitConverter.IsLittleEndian Then
leBytes = BitConverter.GetBytes(v)
beBytes = leBytes.Clone()
Array.Reverse(beBytes)
Else
beBytes = BitConverter.GetBytes(v)
leBytes = beBytes.Clone()
Array.Reverse(leBytes)
End If
Console.WriteLine("Little-Endian : {0}", BitConverter.ToString(leBytes))
Console.WriteLine("Big-Endian : {0}", BitConverter.ToString(beBytes))
'读取:先转成和当前系统系统Endian一致'
If Not BitConverter.IsLittleEndian Then
Array.Reverse(leBytes)
End If
Console.WriteLine("Little-Endian to Int32 : &H{0:X8}", BitConverter.ToInt32(leBytes, 0))
If BitConverter.IsLittleEndian Then
Array.Reverse(beBytes)
End If
Console.WriteLine("Big-Endian to Int32 : &H{0:X8}", BitConverter.ToInt32(beBytes, 0))
Console.ReadLine()
End Sub
End Module
Input Value: &H12345678
Little-Endian : 78-56-34-12
Big-Endian : 12-34-56-78
Little-Endian to Int32 : &H12345678
Big-Endian to Int32 : &H12345678