Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert integer to binary

Tags:

python

I have an integer which I want to convert to binary and store the string of bits in an one-dimensional array starting from the right. For example, if the input is 6 then it should return an array like [1,1,0]. How to do it in python?

like image 363
lovespeed Avatar asked Dec 01 '12 20:12

lovespeed


3 Answers

Solution

Probably the easiest way is not to use bin() and string slicing, but use features of .format():

'{:b}'.format(some_int)

How it behaves:

>>> print '{:b}'.format(6)
110
>>> print '{:b}'.format(123)
1111011

In case of bin() you just get the same string, but prepended with "0b", so you have to remove it.

Getting list of ints from binary representation

EDIT: Ok, so do not want just a string, but rather a list of integers. You can do it like that:

your_list = map(int, your_string)

Combined solution for edited question

So the whole process would look like this:

your_list = map(int, '{:b}'.format(your_int))

A lot cleaner than using bin() in my opinion.

like image 136
Tadeck Avatar answered Sep 21 '22 12:09

Tadeck


You could use this command:

map(int, list(bin(YOUR_NUMBER)[2:]))

What it does is this:

  • bin(YOUR_NUMBER) converts YOUR_NUMBER into its binary representation
  • bin(YOUR_NUMBER)[2:] takes the effective number, because the string is returned in the form '0b110', so you have to remove the 0b
  • list(...) converts the string into a list
  • map(int, ...) converts the list of strings into a list of integers
like image 27
4lbertoC Avatar answered Sep 21 '22 12:09

4lbertoC


>>> map(int, bin(6)[2:])
[1, 1, 0]

If you don't want a list of ints (but instead one of strings) you can omit the map component and instead do:

>>> list(bin(6)[2:])
['1', '1', '0']

Relevant documentation:

  • bin
  • list
  • map
like image 36
arshajii Avatar answered Sep 19 '22 12:09

arshajii