Reputation:
I need to read a file (from right to left), whose reading range can vary, in some cases it can be every 3 bits, 18 bits, etc...
How to do it?
I'll give an example:
The file is:
file : "anyway.rar"
The last 10 hexadecimals of this file are:
1A 2B DF FA 00 15 02 12 EA 1B
I want to read every 3 bits and from right to left. So we started with EA 1B
which in binary is:
11101010 00011011
The reading would be:
011 >> 011 >> 000 >> 101...
If I want to read every 5 bits the reading would be:
11011 >> 10000 >> 11010...
The intention is to make a calculation with each group of bits.
Upvotes: 0
Views: 236
Reputation: 42192
Here is a short but not so simple solution. Allthough you didn't provide code you allready have, I'm sure you have no difficulty reading the string from a file. Some special consideration would have to be made if the input file were binary.
def string_to_bits text, chunksize = 8
StringIO.new(text.unpack('B*').first).each(chunksize).map{|chunk| chunk}
end
Some explanation: String.unpack
formats a string, B*
means in bits, MostSignificant Bits first. See here for the API. It returns an array of one element (hence the following first
)
This string is converted to an enumarable using StringIO
, which has an each(n)
method that chops the string in chunks of the desired length. We convert the enumerator back to an array using map.
Use it like this
puts string_to_bits "this is my text"
#=> ["01110100", "01101000", "01101001", "01110011", "00100000", "01101001", "01110011", "00100000", "01101101", "01111001", "00100000", "01110100", "01100101", "01111000", "01110100"]
and
puts string_to_bits "this is my text", 3
#=> ["011", "101", "000", "110", "100", "001", "101", "001", "011", "100", "110", "010", "000", "001", "101", "001", "011", "100", "110", "010", "000", "001", "101", "101", "011", "110", "010", "010", "000", "001", "110", "100", "011", "001", "010", "111", "100", "001", "110", "100"]
[
Upvotes: 3