1

Possible Duplicate:
Convert an integer to binary without using the built-in bin function

This function receives as a parameter a number in base 10 and should return a list representing the same value expressed in binary as a list of bits, where the first element in the list is the most significant (leftmost) bit.

convert_10_to_2(11) should return [1, 0, 1, 1]

I cannot use the binary function or outside functions, so it has to be done in a more complicated way.

b = ''
while num > 0:
    b = str(num % 2) + b
    num >>= 1
return (b)

Okay I got my code finally up, okay I get '1011', but I need [1,0,1,1], I can't really use any functions such as bin(x) or binary_list. That has been what's taking this question so long.

Community
  • 1
  • 1
user1790201
  • 159
  • 1
  • 1
  • 5

3 Answers3

1

You can initialize a list, then iterate through the string using a for loop and append the value to the list every iteration, like such.

binary_string = convert_10_to_2(11)

binary_list = []

for character in binary_string:
    binary_list.append(int(character))
Jeremy
  • 160
  • 1
  • 1
  • 11
  • Sorry I can't use binary_list either, although I am allowed to use append – user1790201 Nov 23 '12 at 05:29
  • 1
    I'm not exactly sure what you mean. `binary_list` is simply a variable declaring a list, not a function. `binary_list` can be renamed to anything and it will work properly. In other words, it's simply an ordinary list and has no correlation with binary numbers at all, therefore it wouldn't be considered "cheating" in a contest or such. – Jeremy Nov 23 '12 at 05:39
0

bin(X), x is the integer the function returns a binary string

MORE @ python build in functions

Shanil Jevin
  • 45
  • 1
  • 4
0

This will work for both Python 2.x and 3.x:

list(map(int, '{:b}'.format(11)))

Replace 11 with other number, if you wish. Remove enclosing list call, if you do not need support for Python 3.x. Enclose it in function, if you really find it necessary.

Tadeck
  • 132,510
  • 28
  • 152
  • 198