如何将ByteString转换为Int并处理字节序? [英] How to convert a ByteString to an Int and dealing with endianness?

查看:95
本文介绍了如何将ByteString转换为Int并处理字节序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Haskell中读取二进制格式。格式非常简单:四个八位位组指示数据的长度,然后是数据。四个字节代表网络字节顺序中的整数。



如何将四个字节的 ByteString 转换为一个整数?我想要直接转换(在C中为 *(int *)& data ),而不是字典转换。另外,我将如何进行字节排序?



我尝试了Googling,但是有关词典转换的结果只有黄色。



p>

解决方案

二进制包包含一些工具,可从ByteStrings中获取各种大小和字节序的整数类型。

 λ> :set -XOverloadedStrings 
λ>导入合格的Data.Binary.Get作为B
λ> B.runGet B.getWord32be \STX\SOH\SOH\SOH
33620225
λ> B.runGet B.getWord32be忽略\STX\SOH\SOH\SOH跟踪字符
33620225
λ> B.runGet B.getWord32be \STX\SOH\SOH-记得使用`catch`:
***例外:Data.Binary.Get.run在位置0处获取:字节不足b $ b CallStack(来自HasCallStack):
错误,在binary-0.8.5.1:Data.Binary中获取在librarys / binary / src / Data / Binary / Get.hs:351:5中获取


I need to read a binary format in Haskell. The format is fairly simple: four octets indicating the length of the data, followed by the data. The four octets represent an integer in network byte-order.

How can I convert a ByteString of four bytes to an integer? I want a direct cast (in C, that would be *(int*)&data), not a lexicographical conversion. Also, how would I go about endianness? The serialized integer is in network byte-order, but the machine may use a different byte-order.

I tried Googling but that only yold results about lexicographical conversion.

解决方案

The binary package contains tools to get integer types of various sizes and endianness from ByteStrings.

λ> :set -XOverloadedStrings
λ> import qualified Data.Binary.Get as B
λ> B.runGet B.getWord32be "\STX\SOH\SOH\SOH"
33620225
λ> B.runGet B.getWord32be "\STX\SOH\SOH\SOHtrailing characters are ignored"
33620225
λ> B.runGet B.getWord32be "\STX\SOH\SOH" -- remember to use `catch`:
*** Exception: Data.Binary.Get.runGet at position 0: not enough bytes
CallStack (from HasCallStack):
  error, called at libraries/binary/src/Data/Binary/Get.hs:351:5 in binary-0.8.5.1:Data.Binary.Get

这篇关于如何将ByteString转换为Int并处理字节序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆