1

In this Ruby on Rails helper, there is the following method:

# Convert an 8-bit or 16-bit string to an array of big-endian words
# In 8-bit function, characters >255 have their hi-byte silently ignored.
def str2binb(str)
    bin = []
    mask = (1 << $chrsz) - 1
    #for(var i = 0; i < str.length * $chrsz; i += $chrsz)
    i = 0
    while(i < str.length * $chrsz)
        bin[i>>5] ||= 0
        p 'i'
        p i
        p '$chrsz'
        p $chrsz
        p 'str[i / $chrsz]'
        p str[i / $chrsz]
        p 'mask'
        p mask
        bin[i>>5] |= (str[i / $chrsz] & mask) << (32 - $chrsz - i%32)
        i += $chrsz
    end
    return bin
end

When run, this error occurs on the bin[i>>5] |= (str[i / $chrsz] & mask) << (32 - $chrsz - i%32) line:

ActionView::Template::Error (undefined method `&' for "J":String)

I don't understand how & is being used in this instance. How can I resolve this error? I am using Rails 3.2.0 and Ruby 1.9.2.

Here is the logging output:

"i"
0
"$chrsz"
8
"str[i / $chrsz]"
"J"
"mask"
255

1 Answer 1

4

My guess is that this script is working on Ruby 1.8 but fails in Ruby 1.9 because Ruby1.9 outputs b when accessing "bla"[0] instead of the ASCII value of the char as it used to be in Ruby1.8.

You should be able to replace the problematic line by this :

bin[i>>5] |= (str.getbyte(i / $chrsz) & mask) << (32 - $chrsz - i%32)

Or using ord instead :

bin[i>>5] |= (str[(i / $chrsz)].ord & mask) << (32 - $chrsz - i%32)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.