除了Erlang之外,还有其他语言支持位串吗?

j8yoct9x  于 2022-12-08  发布在  Erlang
关注(0)|答案(5)|浏览(149)

我经常处理使用某种类型的COMMAND交换信息的“二进制”协议|长度|PARAMETERS结构,其中PARAMETERS是任意数量的TAG|长度|VALUE元组。Erlang通过模式匹配快速提取消息中的值,例如:
M = <<1, 4, 1, 2, 16#abcd:16>>. <<1,4,1,2,171,205>>
使用M位字符串(COMMAND命令后的消息|长度|PARAMETERS格式),我可以利用Erlang模式匹配来提取命令、长度、参数:
<<Command:8,Length:8,Parameters/binary>> = M. <<1,4,1,2,171,205>> Parameters. <<1,2,171,205>>
对于管理面向“位-半字节-字节”的协议来说,这是非常宝贵的!
是否有其他语言接近于支持这样的语法,甚至通过一个附加库?

shyt4zoc

shyt4zoc1#

https://pypi.python.org/pypi/bitstring/3.1.3 for python这样的东西允许你在同一级别上做很多工作。
在您的示例中:

from bitstring import BitStream
M = BitStream('0x01040102abcd')
[Command, Length, Parameters] = M.readlist('hex:8, hex:8, bits')

给出Parameters作为BitStream('0x0102abcd')

nx7onnlm

nx7onnlm2#

OCaml does, via the bitstring camlp4 extension: https://code.google.com/p/bitstring/

let bits = Bitstring.bitstring_of_file "image.gif" in
  bitmatch bits with
  | { ("GIF87a"|"GIF89a") : 6*8 : string; (* GIF magic. *)
      width : 16 : littleendian;
      height : 16 : littleendian } ->
      printf "%s: GIF image is %d x %d pixels" filename width height
  | { _ } ->
      eprintf "%s: Not a GIF image\n" filename

Another OCaml library that's not quite as bit-oriented but permits mapping of C values is cstruct : https://github.com/mirage/ocaml-cstruct
This lets you write code inline such as:

cstruct pcap_header {
  uint32_t magic_number;   (* magic number *)
  uint16_t version_major;  (* major version number *)
  uint16_t version_minor;  (* minor version number *)
  uint32_t thiszone;       (* GMT to local correction *)
  uint32_t sigfigs;        (* accuracy of timestamps *)
  uint32_t snaplen;        (* max length of captured packets, in octets *)
  uint32_t network         (* data link type *)
} as little_endian

(see the README of both projects for more information)

m0rkklqb

m0rkklqb3#

C当然有一个相对未知的位字段特性。http://en.m.wikipedia.org/wiki/Bit_field

ubbxdtey

ubbxdtey4#

除了已经提到的(Ocaml、Erlang、Python、C),我至少还包括Racket [1]、SmallTalk / Squeak [2]、JavaScript [3]、Elixr [4](我知道这是在Erlang BEAM VM上运行的,但我没有看到提到)和Haskell [5]
Gustafsson和Sagonas[6]的论文“Erlang中BitStream编程的应用、实现和性能评估”中有一个简短的(3页)部分,标题为“实现”,涵盖了实现该系统的细节以及有效的抽象,因此您可以将其引入一种新的语言,而不会遇到太多麻烦。
1个字符
第二个:https://eighty-twenty.org/2020/10/07/bit-syntax-for-smalltalk
3:https://github.com/squaremo/bitsyntax-js
第四章:
第五章:
第六章:

plupiseo

plupiseo5#

为什么说它不值钱?

1> M = <<1, 4, 1, 2, 16#abcd:16>>.                       
<<1,4,1,2,171,205>>
2> <<Command:8,Length:8,Parameters/bitstring>> = M.      
<<1,4,1,2,171,205>>
3> <<Bit:1,Nible:4,Byte:8,Rest/bitstring>> = Parameters.
<<1,2,171,205>>
4> Bit.                                                 
0
5> Nible.                                               
0
6> Byte.                                                
32
7> Rest.                                                
<<85,121,5:3>>
8>

相关问题