Integer_conversion = 0 # Variable to keep the track of sum, this will be our decimal representationįor idx,val in enumerate(b_string): # Iterate from right to left Implementation of Approach 2: b_string = bin(99) # For testing purpose, get the binary string representation of 99.ī_string = b_string # Slice off the 0b prefix We just need to iterate the binary string and get the product and then finally the sum of all the products. In python, we can get the multipliers(increasing powers of two) using the left shift operator. Refer the below diagram for better understanding: Convert binary to decimal form Product = 0 x 2^2.Īt last, the summation of all the products gives us the decimal form of the binary representation. The third bit from the right, 0 gets multiplied to 2^2. The second bit from the right, 1, gets multiplied to 2^1. The rightmost bit, 1, gets multiplied to 2^0. Now that we have multipliers, we then multiply them with the respective digits they are assigned to. Starting from right towards the left(the lowest bit to the highest) we multiply the digits in binary representation with a power of two.įor the rightmost bit, the multiplier is 2^0įor the second position from the right, the multiplier is 2^1.įor the third position from the right, the multiplier is 2^2. Now, there is a multiple for each digit in binary representation. Int(x = b_string, base = 2) # Convert to base 2.Īpproach 2: Using bitmasking and left shift operatorīefore moving forward, it is necessary to understand how we convert the binary number to its decimal form. # Now, convert back the binary string to integer with int() and base parameter. Print(b_string) # Print the binary string representation.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |