0

I am looking at the solution for the following coding challenge on Coderbyte:

Using the Ruby language, have the function BinaryReversal(str) take the str 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: if str is "47" then the binary version of this integer is 00101111. Your program should reverse this binary string which then becomes: 11110100 and then finally return the decimal version of this string, which is 244.

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 0s added onto it until it's length is equal to dig. In fact, I don't understand the role of dig at all.

sawa
  • 165,429
  • 45
  • 277
  • 381
Iris
  • 9
  • 3
  • 1
    I don't know Ruby, but my guess would be that it's calculating the zeros needed for left-padding the value to a length that is 8 digits (e.g., `10001` to `00010001` so that the inverted value is correct (`10001000`). – Ken White Dec 20 '17 at 03:37

1 Answers1

1

When str is "47", binary will be assigned "111101".

  binary = str.to_i.to_s(2).reverse

Normally, you represent binary values as 8 characters or 8 bits. At this point, you can't simply convert your binary string back to an integer. "111101" is 61 in binary.

Instead, you need to pad "111101" with zeroes until it has 8 bits. That's what the following code does.

  dig += 8 until dig >= binary.length
  binary += '0' until binary.length == dig

Once you have 8 bits, you can convert it back to an integer.

Derek Hopper
  • 2,110
  • 12
  • 19