Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you want bits, then you have to do both packing and unpacking manually. Neither Ruby nor any other common-use language will do it for you.</p> <p>Your array contains strings that are groups of characters, but you need to build an array of bytes and write those bytes into the file.</p> <p>From this: <code>["010", "1111", "10", "10", "110", "1110", "001", "110", "000", "10", "011"]</code></p> <p>you should build these bytes: <code>01011111 01011011 10001110 00010011</code></p> <p>Since it's just four bytes, you can put them into a single 32-bit number <code>01011111010110111000111000010011</code> that is <code>5F5B8E13</code> hex.</p> <p>Both samples of your code do different things. The first one writes into the file a string representation of a Ruby array. The second one writes 32 bytes where each is either <code>48</code> ('0') or <code>49</code> ('1').</p> <p>If you want bits, then your output file size should be just four bytes.</p> <p>Read about bit operations to learn how to achieve that.</p> <hr> <p>Here is a draft. I didn't test it. Something may be wrong.</p> <pre><code>a = ["010", "1111", "10", "10", "110", "1110", "001", "110", "000", "10", "011"] # Join all the characters together. Add 7 zeros to the end. bit_sequence = a.join + "0" * 7 # "010111110101101110001110000100110000000" # Split into 8-digit chunks. chunks = bit_sequence.scan(/.{8}/) # ["01011111", "01011011", "10001110", "00010011"] # Convert every chunk into character with the corresponding code. bytes = chunks.map { |chunk| chunk.to_i(2).chr } # ["_", "[", "\x8E", "\x13"] File.open("my_huffman.bin", 'wb' ) do |output| bytes.each { |b| output.write b } end </code></pre> <p>Note: seven zeros are added to handle case when the total number of characters is not divisible by 8. Without those zeros, <code>bit_sequence.scan(/.{8}/)</code> will drop the remaining characters.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload