如何将0到9的整数以及加、减、乘、除等数学运算符转换成二进制字符串。
例如:
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
("%08b" % int)
或 ("%08b" % string)
返回固定数量的位。 - jrdi-9.to_s(2)
的意思是将数字 -9 转换为二进制并转换为字符串。=> "-1001"
是表示二进制数的字符串,其中第一位是符号位(0表示正数,1表示负数),后面的三个数字是二进制表示的绝对值。 - user1201917245.to_s(2)
这样的代码比"%b" % 245
更快。 - Green Su借鉴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
是要使用的最小位数)。
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