I am looking at the solution for the following coding challenge on Coderbyte:
Using the Ruby language, have the function
BinaryReversal(str)
take thestr
parameter being passed, which will be a positive integer, take its binary representation, reverse that string of bits, and then finally return the new reversed string in decimal form. For example: ifstr
is"47"
then the binary version of this integer is00101111
. Your program should reverse this binary string which then becomes:11110100
and then finally return the decimal version of this string, which is244
.
The solution is:
def BinaryReversal(str, dig = 8)
binary = str.to_i.to_s(2).reverse
dig += 8 until dig >= binary.length
binary += '0' until binary.length == dig
binary.to_i(2)
end
I don't understand why the binary needs to have 0
s added onto it until it's length is equal to dig
. In fact, I don't understand the role of dig
at all.