5

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?

7 Answers 7

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1; now that {:b} exists, it's time to get rid of bin(x)[2:] abuse.
4
>>> 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:

2 Comments

I wonder why use bin() and slicing instead of existing other options (namely binary formatting in string's .format()). Could you explain this choice?
@Tadeck Either method will work of course, bin just seemed more appropriate to me in this case.
3

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

Comments

1

You can use the bin function if you have Python >= 2.6:

list(bin(6))[2:]

Edit: oops, forgot to convert items to int:

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

Comments

1

In modern Python you can (>python2.5):

>>> bin(23455)
'0b101101110011111'

Discard the first '0b':

>>> [ bit for bit in bin(23455)[2:] ]
['1', '0', '1', '1', '0', '1', '1', '1', '0', '0', '1', '1', '1', '1', '1']

Everything together:

def get_bits(number):
    return [ int(bit) for bit in bin(number)[2:] ]

In 2.5 you will get an NameError: name 'bin' is not defined.

Comments

1

Others answers use bin() for that. It works, but I find that using string operations to do mathematics is a bit... ehm... lame:

def tobits(x):
    r = []
    while x:
        r.append(x & 1)
        x >>= 1
    return r

The tobits(0) will return an empty list. That may be nice or not, depending on what you'll do with it. So if needed treat it as a special case.

Comments

0

You may use numpy.unpackbits.

Here is the detailed link with examples: https://numpy.org/doc/stable/reference/generated/numpy.unpackbits.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.