Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.

Python Binary to Decimal


ghost's Avatar
0 0

When converting binary to decimal using base 16, how would I write a command that tells the program to read only whats in a certain digits place on a user input command?:ninja:


reaper4334's Avatar
Member
0 0

What do you mean ? You mean so it only does it for like every 8 digits ?


ghost's Avatar
0 0

the code would be something like

binary = input  " > " )

if the digit in the 1'splace is 1 add one, if not add nothing
if the digit in the 10's place is 1 add 2, if not add nothing
if the digit in the 100's place is 1 add 4, if not add nothing
so on so on.```

not exact, but i cant figure out how i would translate that without that code (i know the syntax was incorrect i'm just trying to give some examples), if anyone knows the syntax for that type of command (if the digit in the #'s place =), or possibly an easier way i could do this without having to write 256 if conditions/prints, i would greatly appreciate it.:ninja:

ghost's Avatar
0 0

I don't know Python so I'm just gonna make some pseudo code:

Set currentValue to 128.
Step through the binary (assuming it's just 8 characters).
Get the character in the current position (first time the one to the left).
If it is 1 then add the currentValue.
Divide the currentValue by 2 (this makes it match the binary sequence).

Hope it is understandable. ;)


ghost's Avatar
0 0

If I understood you correctly, you want to retrieve the number in a certain position from a value which you had received through user-input. If this is the case, you might want to look into the modulo operator.

~T


richohealey's Avatar
Python Ninja
0 0

modulo? as in % <? no!

what you want to do is use the len() function and the [] brackets within a for loop.

if you're doing what i think you're doing, you want number = raw_input("binary?") out_number = 0 place = 1 for i in range(0, len(number)): if number[i]: out_number += 2 ** place place += 1 print out_number

is that what you meant? if all you want to do is convert from binary to decimal, there is a function to do that, search python.org for the char() function, it's somewhere near that in the documentation.

PM me if you need more, or reply here if you think it's the sort of thing others might need.