문제

I am trying to reproduce a sequence of code from a Python program in C#. In Python I have:

element1, element2 = struct.unpack('!hh', data[2:6])

The above statement unpacks from a "substring" of data in short-short (network byte order) format. The values resulted (element1,element2) are: 96 and 16

My attempt in C# is:

byte[] bytesOfInterval = ASCIIEncoding.ASCII.GetBytes (data.Substring (2, 4));
using (MemoryStream stream = new MemoryStream(bytesOfInterval)) {
    using (BinaryReader reader = new BinaryReader(stream)) {
        Logger.Trace (reader.ReadInt16().ToString());
        Logger.Trace (reader.ReadInt16().ToString());
    }
}

It outputs: 24576 and 4096 .

As you can see the output from the Python program is slightly different from the C# one. To verify the "substrings" (input), I've encoded them in hex format to see if there is any difference. They were both equal to 00600010, hence, the input is the same the output is different. Why?

Notes:

도움이 되었습니까?

해결책

I think it is an endianness problem try this for example

Int16 x1 = 4096;  
var x2 = IPAddress.HostToNetworkOrder(x1);

x2 will be 16 (same for 24576 => 96)

So you can use IPAddress.HostToNetworkOrder method.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top