如何将整数 0..9 和数学运算符 + - * / in 创建为二进制字符串。例如:
0 = 0000,
1 = 0001,
...
9 = 1001
有没有办法在不使用库的情况下使用 Ruby 1.8.6 做到这一点?
您拥有Integer#to_s(base)
并且String#to_i(base)
可以使用。
Integer#to_s(base)
将十进制数转换为表示指定基数的字符串:
9.to_s(2) #=> "1001"
而相反的情况是通过以下方式获得的String#to_i(base)
:
"1001".to_i(2) #=> 9
借鉴 bta 的查找表理念,您可以使用块创建查找表。值在第一次访问和存储时生成以供以后使用:
>> lookup_table = Hash.new { |h, i| h[i] = i.to_s(2) }
=> {}
>> lookup_table[1]
=> "1"
>> lookup_table[2]
=> "10"
>> lookup_table[20]
=> "10100"
>> lookup_table[200]
=> "11001000"
>> lookup_table
=> {1=>"1", 200=>"11001000", 2=>"10", 20=>"10100"}
您自然会使用Integer#to_s(2)
,String#to_i(2)
或"%b"
在实际程序中,但是,如果您对翻译的工作原理感兴趣,此方法使用基本运算符计算给定整数的二进制表示:
def int_to_binary(x)
p = 0
two_p = 0
output = ""
while two_p * 2 <= x do
two_p = 2 ** p
output << ((two_p & x == two_p) ? "1" : "0")
p += 1
end
#Reverse output to match the endianness of %b
output.reverse
end
要检查它是否有效:
1.upto(1000) do |n|
built_in, custom = ("%b" % n), int_to_binary(n)
if built_in != custom
puts "I expected #{built_in} but got #{custom}!"
exit 1
end
puts custom
end
如果您只使用单个数字 0-9,则构建查找表可能会更快,因此您不必每次都调用转换函数。
lookup_table = Hash.new
(0..9).each {|x|
lookup_table[x] = x.to_s(2)
lookup_table[x.to_s] = x.to_s(2)
}
lookup_table[5]
=> "101"
lookup_table["8"]
=> "1000"
使用数字的整数或字符串表示对该哈希表进行索引将产生其作为字符串的二进制表示。
如果您要求二进制字符串长度为一定位数(保持前导零),则更x.to_s(2)
改为sprintf "%04b", x
(其中4
是要使用的最小位数)。
在 ruby Integer 类中, to_s 被定义为接收非必需的参数基数base
,如果要接收字符串的二进制表示,则传递 2。
1.upto(10).each { |n| puts n.to_s(2) }
如果您正在寻找我使用的 Ruby 类/方法,并且我还包括了测试:
class Binary
def self.binary_to_decimal(binary)
binary_array = binary.to_s.chars.map(&:to_i)
total = 0
binary_array.each_with_index do |n, i|
total += 2 ** (binary_array.length-i-1) * n
end
total
end
end
class BinaryTest < Test::Unit::TestCase
def test_1
test1 = Binary.binary_to_decimal(0001)
assert_equal 1, test1
end
def test_8
test8 = Binary.binary_to_decimal(1000)
assert_equal 8, test8
end
def test_15
test15 = Binary.binary_to_decimal(1111)
assert_equal 15, test15
end
def test_12341
test12341 = Binary.binary_to_decimal(11000000110101)
assert_equal 12341, test12341
end
end
我迟到了将近十年,但如果有人仍然来这里并想在不使用像 to_S 这样的内置函数的情况下找到代码,那么我可能会有所帮助。
找到二进制
def find_binary(number)
binary = []
until(number == 0)
binary << number%2
number = number/2
end
puts binary.reverse.join
end