How do you create integers 0..9 and math operators + - * / in to binary strings. For example:
0 = 0000,
1 = 0001,
...
9 = 1001
Is there a way to do this with Ruby 1.8.6 without using a library?
How do you create integers 0..9 and math operators + - * / in to binary strings. For example:
0 = 0000,
1 = 0001,
...
9 = 1001
Is there a way to do this with Ruby 1.8.6 without using a library?
You have
Integer#to_s(base)
andString#to_i(base)
available to you.Integer#to_s(base)
converts a decimal number to a string representing the number in the base specified:while the reverse is obtained with
String#to_i(base)
:I asked a similar question. Based on @sawa's answer, the most succinct way to represent an integer in a string in binary format is to use the string formatter:
You can also choose how long the string representation to be, which might be useful if you want to compare fixed-width binary numbers:
If you are looking for a Ruby class/method I used this, and I have also included the tests:
You would naturally use
Integer#to_s(2)
,String#to_i(2)
or"%b"
in a real program, but, if you're interested in how the translation works, this method calculates the binary representation of a given integer using basic operators:To check it works:
Picking up on bta's lookup table idea, you can create the lookup table with a block. Values get generated when they are first accessed and stored for later:
If you're only working with the single digits 0-9, it's likely faster to build a lookup table so you don't have to call the conversion functions every time.
Indexing into this hash table using either the integer or string representation of a number will yield its binary representation as a string.
If you require the binary strings to be a certain number of digits long (keep leading zeroes), then change
x.to_s(2)
tosprintf "%04b", x
(where4
is the minimum number of digits to use).