How to convert a 5-bit binary string to an alphabetic character?

If I have a 5-bit binary string, such as '01010', how can I convert it to the corresponding alphabet?

( '00000''a'.. '11111''F')

I do this to compress a large set of booleans into a string that can contain only alphabetic characters [a-zA-Z].

+3
source share
3 answers
letters = ('a'..'z').to_a + ('A'..'F').to_a
letters["00000".to_i(2)] # => 'a'
letters["11111".to_i(2)] # => 'F'
letters["01010".to_i(2)] # => 'k'
+3
source

General Encoding Version

s = '00001'
code = s.to_i(2)
puts (?a.ord + code).chr  # => b
+3
source

LBg-:

class SomeClass
    @@letters = (('a'..'z').to_a+('A'..'F').to_a)
    def self.decode str
        str.chars.map do |c|
            c = @@letters.index(c).to_s(2)
            while c.length < 5
                c = "0#{c}"
            end
            c
        end.join('').split('').map do |c|
            if c == '1'
                true
            else
                false
            end
        end
    end
    def self.encode *bools
        str = ''
        until bools.length == 0
            five = ''
            5.times do
                five += bools.length > 0 ? (bools.shift() ? '1' : '0') : '0'
            end
            str += @@letters[five.to_i(2)]
        end
        str
    end
end

, , , , .

0

Source: https://habr.com/ru/post/1793444/


All Articles