# Binary Bits to Decimal Numbers

i am interested to get a python module/script that does the following :

Input :

Binary Values

10011100011

Output:

Based on the above binary values/bits, convert the bits into dec equivalent

1024 + not_set + not_set + 128 + 64 + 32 + not_set + not_set + not_set + 2 + 1

Thanks a bunch.

###### Who is Participating?

Software EngineerCommented:
Like this?

Output:

C:\>python plus.py
1024 +  not_set +  not_set +  128 +  64 +  32 +  not_set +  not_set +  not_set +  2 +  1

``````val = '10011100011';
L = len( val );
plus = '';
for i in range( L ) :
c = val[ i ];
if c == '1' :
print plus, int( ( '1' + ( '0' * ( L - 1 - i ) ) ), 2 ),
else :
print plus, 'not_set',
plus = '+ ';
``````
0

Software EngineerCommented:
you mean like:

``````>>>
>>> int( '10011100011', 2 )
1251
>>>>>> hex( 1251 )
'0x4e3'
``````
0

Software EngineerCommented:
Oh, you really want that output?

1024 + not_set + not_set + 128 + 64 + 32 + not_set + not_set + not_set + 2 + 1

one moment.
0

Author Commented:
:) Yes
0

Software EngineerCommented:
Do you like this better?

Output:
1024 +  not_set +  not_set +  128 +  64 +  32 +  not_set +  not_set +  not_set +  2 +  1
``````val = '10011100011'
result = [];
pot = 1
while val :
val, c = val[ :-1 ], val[ -1 ]
if c == '1' :
result.append( pot );
else :
result.append( 'not_set' )
pot *= 2

result.reverse();
plus = '';
for c in result :
print plus, c,
plus = '+ ';
``````
0

Commented:
I'd like more structured version:
``````def p2(n):
p = 1
s = []
while n:
s.append(n&1 and p or 0)
p *= 2
n /= 2
return s[::-1]

value = '10011100011'
print ' + '.join(str(b or 'not set') for b in p2(int(value, 2)))
``````
0

Software EngineerCommented:
the "or 0" appears to be unnecessary...

interesting solution though
``````def p2(n):
p = 1
s = []
while n:
s.append(n&1 and p)
p *= 2
n /= 2
return s[::-1]

value = '10011100011'
print ' + '.join(str(b or 'not set') for b in p2(int(value, 2)))
``````
0

Author Commented:
Thanks Bros! Cheers.
W
0

Software EngineerCommented:
Thanks for the grade & points.

Good luck & have a great day.
0

Author Commented:
You star! HonorGod! Thanks for helping me out too.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.