I love Ruby very much and now Ruby is my first language.But now I meet a
problem on Ruby.I want to do as follows:
1:Open a file in binary mode
2:Shift the bit in a algorithm
3:Save the file
I don’t know how to shift the bit stream in Ruby.Can any one give me an
advice???
On Feb 7, 2007, at 9:13 PM, Minxing L. wrote:
I love Ruby very much and now Ruby is my first language.But now I
meet a
problem on Ruby.I want to do as follows:
1:Open a file in binary mode
2:Shift the bit in a algorithm
3:Save the file
I don’t know how to shift the bit stream in Ruby.Can any one give
me an
advice???
The bit-shift operator is <<. Example:
n = 1
n = n < 4 (left shift)
n < 2 (right shift)
Regards, Morton
On Feb 7, 2007, at 9:13 PM, Minxing L. wrote:
I love Ruby very much and now Ruby is my first language.But now I
meet a
problem on Ruby.I want to do as follows:
1:Open a file in binary mode
2:Shift the bit in a algorithm
3:Save the file
I don’t know how to shift the bit stream in Ruby.Can any one give
me an
advice???
I should also mention that >> is a bit-shift operator, too. Works the
opposite of <<.
n = 4
n = n >> 2 # => 1
n >> -1 # => 2
Regards, Morton
On 2/7/07, Minxing L. [email protected] wrote:
I love Ruby very much and now Ruby is my first language.But now I meet a
problem on Ruby.I want to do as follows:
1:Open a file in binary mode
2:Shift the bit in a algorithm
3:Save the file
I don’t know how to shift the bit stream in Ruby.Can any one give me an
advice???
As mentioned before, you can use the >> and << operators to perform
bit shift operations, but these only work with integers. You will need
to use the pack and unpack methods to convert the strings you read
from the file into integers.
str = IO.read(‘myfile’)
ary = str.unpack(‘N*’)
ary.map! {|int| int >> 2}
str = ary.pack(‘N*’)
File.open(‘anotherfile’,‘w’) {|fd| fd.write str}
This example assumes you have a file full of 32-bit integers in
big-endian format. It will shift each integer 2 bits to the right.
Blessings,
TwP