主机字节顺序和网络的HostAddress6

时间:2016-06-15 21:09:29

标签: haskell networking ipv6 endianness

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

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

  1. 使用byteorder确定当前的主机顺序,如果是little-endian,请在每个单词上使用byteSwap32(或者base-compat中使用putWord32be

    case byteOrder of
        LittleEndian -> byteSwap32
        _ -> id
    
  2. 使用谷物getWord32host序列化单词并立即使用EmberFire 2.0(或替代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
    
  4. 有什么更好或更方便吗?

1 个答案:

答案 0 :(得分:2)

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

getSystemEndianness :: Endianness

获取当前的CPU endianess

fromLE64 :: Word64 -> Word64

从LE64到平台endianess

fromBE64 :: Word64 -> Word64

与上述相同,但来自BE 64

toLE64 :: Word64 -> Word64

从CPU的Endianess到LE64

toBE64 :: Word64 -> Word64

从CPU的Endianess到BE64

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

相关问题