【问题标题】:Converting an int to bit array in OCaml在 OCaml 中将 int 转换为位数组
【发布时间】:2017-03-26 19:29:27
【问题描述】:

我有一个 int,假设是 6,我想将它转换为位数组。

bArr.(0) = 1
bArr.(1) = 1
bArr.(2) = 0

有什么功能可以为我做这件事吗?

我需要它是一个数组,以便我可以将它传递给接收布尔数组的其他函数。

【问题讨论】:

    标签: arrays ocaml bit bitarray


    【解决方案1】:

    整数x的第n位可以用以下函数计算:

      let nth_bit x n = x land (1 lsl n) <> 0
    

    可以使用Array.init函数创建和初始化数组:

      let bitarray length x = Array.init length (nth_bit x)
    

    这将在 LSB(最低有效位)一阶中创建一个布尔数组。如果你需要一个整数数组,那么你可以使用函数nth_bit_value 而不是nth_bit

      let nth_bit_value x n = if nth_bit x n then 1 else 0
    

    我将把它留作练习,以获取 MSB 顺序的数组。

    【讨论】:

    • 我怎么可以只用1个参数调用nth_bit?
    • nth_bit 是一个柯里化函数,因此将其应用于第一个参数(x)会返回一个接受其余参数(在本例中为 n)的函数。跨度>
    • 称为部分应用。当您有一个带有n 参数的函数时,您可以将k 参数传递给它,结果将是一个接受其余n-k 参数的函数。在我们的例子中,(nth_bit x)(fun i -&gt; nth_bit x i) 相同
    【解决方案2】:
    let int_to_bArr i =
      let rec int_to_bit acc i =
        if i=0 then acc
        else int_to_bit (i land 1::acc) (i lsr 1)
      in
      let l=int_to_bit [] i in
      Array.of_list  l           
    ;;
    

    测试

    # int_to_bArr 6;;
    - : int array = [|1; 1; 0|]
    

    或者

    let int_to_bArr i =
      let rec int_to_bool acc i =
        if i=0 then acc 
        else int_to_bool (((i land 1)=1)::acc) (i lsr 1)
      in
      let l=int_to_bool [] i in
      Array.of_list  l 
    ;;
    
    # int_to_bArr 6;;
    - : bool array = [|true; true; false|]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多