主机字节顺序和网络的 HostAddress6

Host byte order and network's HostAddress6

是否有一些现成的函数可以在 big/little/host-endian 表示之间转换 Word32Word64?正如评论中指出的那样,如果正确执行(反)序列化,则不需要这样做,但在处理低级代码时在某些特定情况下可能会很方便。

我找到了以下解决方案,但都不完美:

  1. 使用byteorder to determine the current host order, and if little-endian, use byteSwap32 on each word (or alternatively the one from base-compat

    case byteOrder of
        LittleEndian -> byteSwap32
        _ -> id
    
  2. 用谷物的 putWord32be and immediately read them with getWord32host 序列化单词(或者 putWord32host 并用 getWord32be 阅读)。这增加了更多的重量级依赖性,但为转换为其他格式提供了更大的灵活性。

    either (error "Unexpected error when converting ip address") id
    . runGet getWord32host . runPut . putWord32be
    
  3. 导入原生函数:

    foreign import ccall unsafe "htonl" htonl :: Word32 -> Word32
    foreign import ccall unsafe "ntohl" ntohl :: Word32 -> Word32
    

有没有更好或者更方便的?

是的,cpu 包中的 System.Endian 模块中有。为了我的目的,我也需要它。 它有许多实用功能,例如:

getSystemEndianness :: Endianness

获取当前 CPU 字节顺序

fromLE64 :: Word64 -> Word64

从 LE64 到平台字节序

fromBE64 :: Word64 -> Word64

同上,但从 BE 64 开始

toLE64 :: Word64 -> Word64

从 CPU 的字节序到 LE64

toBE64 :: Word64 -> Word64

从 CPU 的字节序到 BE64

请注意,该模块为 Word32 和 Word16 提供了相同的功能: https://hackage.haskell.org/package/cpu-0.1.2/docs/System-Endian.html