如何打开位的数组中的一个位串,其中每一位重新presents在Ruby中1布尔 [英] How do I turn an array of bits in an bitstring where each bit represents one boolean in Ruby

查看:166
本文介绍了如何打开位的数组中的一个位串,其中每一位重新presents在Ruby中1布尔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是pretty言自明。我想变成像 [真,真,假,真] 成以下比特串1101。

The question is pretty self explanatory. I want to turn something like [true, true, false, true] into the following bitstring 1101.

我想我需要使用Array.pack,但我无法弄清楚究竟是如何做到这一点。

I assume I need to use Array.pack, but I can't figure out exactly how to do this.

推荐答案

这真的取决于你想如何准确地重新present布尔数组。

It really depends on how exactly you want to represent the boolean Array.

有关 [真,真,假,真] ,它应该是 0b1101 0b11010000 ?我认为是前者,你可能会得到这样的:

For [true, true, false, true], should it be 0b1101 or 0b11010000? I assume it's the former, and you may get it like this:

data = [true, true, false, true]
out = data
  .each_slice(8) # group the data into segments of 8 bits, i.e., a byte
  .map {|slice|
    slice
      .map{|i| if i then 1 else 0 end } # convert to 1/0
      .join.to_i(2)                     # get the byte representation
  }
  .pack('C*')
p out #=> "\r"

PS。根据您的需求可能有进一步的尾数问题。

PS. There may be further endian problem depending on your requirements.

这篇关于如何打开位的数组中的一个位串,其中每一位重新presents在Ruby中1布尔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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