C# big-endian UCS-2

前端 未结 3 2077
Happy的楠姐
Happy的楠姐 2020-12-06 08:58

The project I\'m currently working on needs to interface with a client system that we don\'t make, so we have no control over how data is sent either way. The problem is tha

3条回答
  •  粉色の甜心
    2020-12-06 09:20

    UCS-2 is so close to UTF-16 that Encoding.BigEndianUnicode will almost always suffice.

    The issue (comments) around reading the length prefix (as big-endian) is more correctly resolved via shift operations, which will do the right thing on all systems. For example:

    Read4BytesIntoBuffer(buffer);
    int len =(buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | (buffer[3]); 
    

    This will then work the same (at parsing a big-endian 4 byte int) on any system, regardless of local endianness.

提交回复
热议问题