ntohs() and ntohl() equivalent?

喜你入骨 提交于 2019-12-18 05:27:15

问题


Are there net to host conversion functions in C#? Googling and not finding much. :P


回答1:


IPAddress.HostToNetworkOrder and IPAddress.NetworkToHostOrder?

Each method has overloads for 16, 32 and 64 bit integers.




回答2:


@jon-skeet's answer is the most accurate according to your question. However, 'ntoh_' and 'hton_' C functions are extensively used in order to translate between little-endian and big-endian computer architectures.

If your intention is to perform endianess conversions, there is a BitConverter class (static class in the core assembly) that brings you a more suitable way. Specially when:

  • Working with array of bytes (widely used in file or network streams).
  • Detecting endianess architecture of the runtime machine.
  • Converting basic structures beyond integers (booleans, decimals) without typecasting.
  • Your code is not related to network operations (System.Net namespace).



回答3:


The System.Memory nuget package includes the System.Buffers.Binary.BinaryPrimitives static class, which includes static methods for dealing with "endianness", including many overloads of ReverseEndianness. On dotnet core, HostToNetWorkOrder is implemented using these ReverseEndianness methods . On a little-endian architecture (which I think is all that support .NET) HostToNetworkOrder and ReverseEndianness methods have identical performance on dotnetcore.

On dotnet framework (net461) however, the performance of calling HostToNetworkOrder is slightly (not quite 2x) slower than calling ReverseEndianness.

I believe that the JIT compiler is actually special casing these methods to invoke the BSWAP x86 instruction. If you exactly duplicate the implementation of the ReverseEndianness(long) method in your own codebase, it will be nearly 4x slower than calling the System.Memory implementation; suggesting there is JIT magic happening.



来源:https://stackoverflow.com/questions/2420227/ntohs-and-ntohl-equivalent

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!