开发者

Reading signed and unsigned values from a stream in both byte orders

I need to read signed and unsigned 8 bit, 16 bit and 32 bit values from a file stream which may be little-endian or big-endian (it happens to be a tiff file which carries the byte order indicator at the start).

I initially started by writing my own functions to read the values and was able to do so for unsigned values. e.g.

Public Function ReadUInt32() As UInt32
    Dim b(4) As Byte
    input.Read(b, 0, 4)
    Dim out As UInt32 = CUInt(If(IsBigEndian, b(0), b(3))) << 24
    out += CUInt(If(IsBigEndian, b(1), b(2))) << 16
    out += CUInt(If(IsBigEndian, b(2), b(1))) << 8
    out += CUInt(If(IsBigEndian, b(3), b(0)))
    Return out
End Function

But then I started looking at signed values and my brain broke.

As an alternative, I found the IO.BinaryReader which will let me read signed values directly but doesn't seem to have any way to indicate that the data is big-endian or little-endian.

Is there a nice开发者_StackOverflow中文版 way of handling this? Failing that, can someone tell me how to convert multiple bytes into signed values (in both byte orders)?


It's not ideal, but you can use the various overloads of the HostToNetworkOrder and NetworkToHostOrder methods from the System.Net.IPAddress class to do signed-integer endian conversion.


Have you taken a look at the BitConverter Class?

http://msdn.microsoft.com/en-US/library/system.bitconverter_members(v=VS.80).aspx

Some byte shuffling and a call to ToUInt32 should get what you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜