# 8. a bit of this or that - alternative

#1

I expect to be able to work with the binary number, but it's automatically converted to an int when stored in a variable. How do I keep it to just a string of "0b1110"( for example) instead of it being stored as '14'

``````a = 0b1110
b = 0b101
print a, b``````

#2

String literals have quotes around them. Integers are integers regardless of if you write them in base10 or base2, they aren't being converted, it's the same thing. You can print an integer as base2 by using the `bin` function or by using string formatting:

``````>>> '{:b}'.format(55)
'110111'
>>> bin(55)
'0b110111'
>>> type(0b110111)
<class 'int'>``````

#3

i got it fingered out!

like the others, I know they meant figure it out on paper. but I wanted to try to code an alternative.

``````def counting_bits(a,b):
a = '{:b}'.format(a)
b = '{:b}'.format(b)
a.zfill(len(b))
b.zfill(len(a))
for i in a:
ans = (
['1'
for i in range(len(a))
if a[i] != 0 or b[i] != 0 ])
ans = '0b' + ''.join(ans)
ans = int(ans, 2)

return bin(ans)

print counting_bits(0b1110,0b101)``````

#4

That loop of yours looks like it's doing the exact same thing over and over

I find that having more than one NOT in an expression makes it very difficult to read:

`a[i] != 0 or b[i] != 0`

I would write that as:

`a[i] or b[i]`

I also don't think any elements of a/b will be the integer 0 so the outcome of that expression is always the same

#5

``````def counting_bits(a,b):
a = '{:b}'.format(a)
b = '{:b}'.format(b)
a = a.zfill(len(b))
b = b.zfill(len(a))
ans = ['0' if a[i] == '0' and b[i] == '0' else '1' for i in range(len(a))]
ans = '0b' + ''.join(ans)
ans = int(ans, 2)
return ans

print bin(counting_bits(0b1110,0b101))``````

#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.