I am trying to recursively convert int to binary string but I don’t really understand how the whole positive int to binary string conversion works.
Also found out that apparently each position is like a representation of the power of 2.
Any explanation as to how to convert a positive int to a string representation as shown in the Googled example above is extremely helpful.
Here is a recursive implementation for converting an int to a binary string, which is what I think this question is asking for:
Note that this is only useful as an exercise in recursion, if you are just trying to get at the binary string use the built-in
bin()function.This works because
i&1will give you the last bit ini(either0or1), andi>>1will shift all bits inito the right by one bit (equivalent to division by 2). Here is an explanation of how this would work for 6 (1102):