Edges to Rubies The Complete SketchUp Tutorial


Transformation matrix diagram.

Appendix BFR—Bit Fiddling in Ruby

You can take the man out of assembly language, but you can't take the assembly language out of the man.

For background on the reason for a bitmap encoding the "V"s and "I"s, see Appendix BFJ, Bit Fiddling in JavaScript.

Decoding the Map Length

The first three characters of the bitmap encode the number of "V"s and "I"s in the decoded string. These are encoded in six bits per character in the first 3 characters, with the most significant digits on the left. 48 is added to each bit pattern to encode using ASCII characters 48 through 111.

In the following method @@base is 48 and @map is the bitmap encoded in a character string.

    def getLength()
        @length = 64 * 64 * ( @map[0] - @@base )
        @length += 64 * ( @map[1] - @@base )
        @length += @map[2] - @@base;
    end

It turns out that this process in Ruby doesn't really require any bit fiddling. It took a lot in JavaScript to do the encoding.

Decoding a Single Word

In this class @@vismap_powers is the array [32, 16, 8, 4, 2, 1] integers with a single bit set in each. If you & (logical and) one of these patterns with the word you are decoding, you get a positive value if the bit in the word and the mask are both set (one-valued); otherwise you get zero. Looping over the powers effectively tests bits working from left to right.
    def getVisFromWord( word )
        v = ''
        @@vismap_powers.each do |p|
            v += ( p & word ) > 0 ? 'V' : 'I'
        end
        return v
    end

In decoding, of course, you are looking at the bits but generating "V"s and "I"s.

Decoding the Bitmap

This is a simple matter of decoding first the length and then marching down the rest of the map decoding one character at a time into its six bit values.

This may result in excess "V"s or "I"s as you get six values from the last character (which is padded with excess zeros unless the original input is a multiple of six long). The code that uses the "V"s and "I"s loops over the @length, ignoring the excess characters.

The full code is in vismap2.rb which is installed in .../Plugins/vismap2/.


View of apartment contents. Transformation matrix diagram.