Search code examples
rubyarraysbinarypack

How do I turn an array of bits in an bitstring where each bit represents one boolean in Ruby


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

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


Solution

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

    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. There may be further endian problem depending on your requirements.