Как найти двоичную запись числа в питоне

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Python bin() function returns the binary string of a given integer.

    Syntax:  bin(a)

    Parameters : a : an integer to convert

    Return Value : A binary string of an integer or int object.

    Exceptions : Raises TypeError when a float value is sent in arguments.

    Python bin() Example

    Example 1: Convert integer to binary with bin() methods

    Python3

    Output:

    0b1100100

    Example 2: Convert integer to binary with user define function

    Python3

    def Binary(n):

        s = bin(n)

        s1 = s[2:]

        return s1

    print("The binary representation of 100 (using bin()) is : ", end="")

    print(Binary(100))

    Output: 

    The binary representation of 100 (using bin()) is : 1100100

    Example 3: user-defined object to binary using bin() and __index()__

    Here we send the object of the class to the bin methods, and we are using python special methods __index()__ method which always returns positive integer, and it can not be a rising error if the value is not an integer. 

    Python3

    class number:

        num = 100

        def __index__(self):

            return(self.num)

    print(bin(number()))

    Output:

    0b1100100

    This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 

    Last Updated :
    17 Sep, 2021

    Like Article

    Save Article

    In this tutorial, you’ll learn how to use Python to convert an int to a binary, meaning converting an integer to a binary string.

    You’ll learn a brief overview of this conversion and how binary strings are represented in computers. Then, you’ll learn how to use four different methods to use Python to convert int to binary. These include, the bin() function, string formatting, f-strings, the format() function, as well as naive implementation without the use of any functions.

    The Quick Answer: Use the format() Function

    Quick Answer - Python int to binary Convert Integer to Binary

    What are Binary Strings for Integers?

    The common integer system that we’re used to, the decimal system, uses a base of ten, meaning that it has ten different symbols. These symbols are the numbers from 0 through to 9, which allow us to make all combinations of numbers that we’re familiar with.

    Binary strings, on the other hand, use a base of two, meaning that they only have two numbers to express different numbers. These numbers are either 0 or 1. While the binary number system has been in use in different ancient civilizations (such as Egypt and India), it is used extensively in electronics and computer system in modern times.

    In the next sections, you’ll learn how to use Python to convert an integer to a binary using the bin() function.

    Want to learn how to get a file’s extension in Python? This tutorial will teach you how to use the os and pathlib libraries to do just that!

    The Python bin() function is short for binary and allows us to convert an integer to a binary string, which is prefixed by '0b'. In later section, you’ll learn how to convert the integer using Python without the prefix.

    Let’s take a look at how we can turn a positive integer into a binary string using Python:

    # Convert an integer to a binary string using Python bin()
    positive = 123
    binary = bin(positive)
    print(binary)
    
    Returns: '0b1111011'

    We can see that a binary string with the '0b' prefix has been returned.

    Let’s check the type of the statement that’s been returned, using the built-in type() function:

    # Checking the type of our binary string
    positive = 123
    binary = bin(positive)
    print(type(binary))
    # Returns:
    # <class 'str'>

    We can see here that the function returned a string, as expected.

    Now let’s see what happens when we pass in a negative integer and try to use Python to convert it to binary string:

    # Convert an integer to a binary string using Python bin()
    negative = -123
    binary = bin(negative)
    print(binary)
    
    Returns: '-0b1111011'

    We can see that there’s also a '-' prefix to our string, letting us know that the number is a negative value.

    In the next section, you’ll learn how to use Python string formatting to convert an int to a binary string.

    Want to learn how to use the Python zip() function to iterate over two lists? This tutorial teaches you exactly what the zip() function does and shows you some creative ways to use the function.

    Use Python String Formatting to Convert Int to Binary

    If you’re wanting to convert a Python integer to a binary string without the '0b' prefix, you can use string formatting.

    Python string formatting allows us to define different format types for passing in values. In this case, we’ll pass in the format code of '{0:b}', which allows us to convert an integer to binary.

    Let’s see how we can pass in a few integer values, both positive and negative, and convert them to binary string using string formatting:

    # Convert an integer to a binary string using Python string formatting
    positive = 123
    negative = -123
    
    positive_binary = '{0:b}'.format(positive)
    negative_binary = '{0:b}'.format(negative)
    
    print(f'{positive_binary=}')
    print(f'{negative_binary=}')
    
    # Returns:
    # positive_binary='1111011'
    # negative_binary='-1111011'

    We can see here that this method returns the same strings, without the '0b' prefix.

    In the next section, you’ll learn Python f-strings to convert an int to a binary string.

    Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.

    Use Python f-strings to Convert Int to Binary

    Python f-strings allow us to make string formatting a little bit more intuitive. They also allow us to apply formatting to our strings in similar ways to traditional string formatting.

    As a quick refresher on Python f-strings, they’re strings introduced in Python versions 3.6 and above, and are created by prefixing either a 'f' or 'F' to the string.

    Let’s see how we can convert an integer to a binary string using Python f-strings. We’ll try this for the same positive and negative integers as above:

    # Convert an integer to a binary string using Python f-strings
    positive = 123
    negative = -123
    
    positive_binary = f'{positive:b}'
    negative_binary = f'{negative:b}'
    
    print(f'{positive_binary=}')
    print(f'{negative_binary=}')
    
    # Returns:
    # positive_binary='1111011'
    # negative_binary='-1111011'

    We can see here that the same values are returned. Python f-strings may not work in all versions of Python, but they are intuitive and easy to understand.

    In the next section, you’ll learn how to use the Python format() function to convert an int to a binary string.

    Want to learn more about Python f-strings? Check out my in-depth tutorial, which includes a step-by-step video to master Python f-strings!

    Use Python format to Convert Int to Binary

    Another way to convert a Python integer to a binary string is to use the built-in format() function. The format() function takes value and a format spec as its arguments.

    Because of this, we can pass in a value (in this case, an integer) and a format spec (in this case “b”), to specify that we want to return a binary string.

    Let’s see how we can accomplish this using Python:

    # Convert an integer to a binary string using Python format()
    positive = 123
    negative = -123
    
    positive_binary = format(positive, 'b')
    negative_binary = format(negative, 'b')
    
    print(positive_binary)
    print(negative_binary)
    
    # Returns:
    # positive_binary='1111011'
    # negative_binary='-1111011'

    This is also a very readable way in which we can convert Python integers to string. The function makes it clear that we’re converting a value to something else, even specifying a type.

    In the final section, you’ll learn how to convert an int to a binary string from scratch.

    Want to learn how to calculate and use the natural logarithm in Python. Check out my tutorial here, which will teach you everything you need to know about how to calculate it in Python.

    Convert an Int to Binary in Python without a Function

    In this final section, you’ll learn how to convert how to create a naive method to convert a Python integer to a string. You’ll actually create a custom function that does this, but be able to understand how the conversion works.

    Practically speaking, this is not something you’d really need to do, but it can be a helpful task to understand for programming interviews.

    # Convert an integer to a binary string using a custom function
    def int_to_binary(integer):
        binary_string = ''
        while(integer > 0):
            digit = integer % 2
            binary_string += str(digit)
            integer = integer // 2
        binary_string = binary_string[::-1]
        return binary_string
    
    print(int_to_binary(123))
    
    # Returns: 
    # 1111011

    Check out some other Python tutorials on datagy, including our complete guide to styling Pandas and our comprehensive overview of Pivot Tables in Pandas!

    Conclusion

    In this post, you learned how to use Python to convert int to binary, meaning how to convert integer values to binary strings. You learned how to do this using a number of different methods, including using the Python bin() function, string formatting, f-strings, the format() function, and without any functions at all.

    If you want to learn more about the Python bin() function, check out the official documentation here. To learn more about the Python format() function, you can find the official documentation here.

    In order to convert an integer to a binary, I have used this code :

    >>> bin(6)  
    '0b110'
    

    and when to erase the ‘0b’, I use this :

    >>> bin(6)[2:]  
    '110'
    

    What can I do if I want to show 6 as 00000110 instead of 110?

    just-Luka's user avatar

    just-Luka

    3671 gold badge5 silver badges19 bronze badges

    asked May 2, 2012 at 9:31

    Smith's user avatar

    1

    >>> '{0:08b}'.format(6)
    '00000110'
    

    Just to explain the parts of the formatting string:

    • {} places a variable into a string
    • 0 takes the variable at argument position 0
    • : adds formatting options for this variable (otherwise it would represent decimal 6)
    • 08 formats the number to eight digits zero-padded on the left
    • b converts the number to its binary representation

    If you’re using a version of Python 3.6 or above, you can also use f-strings:

    >>> f'{6:08b}'
    '00000110'
    

    TrebledJ's user avatar

    TrebledJ

    8,6247 gold badges25 silver badges47 bronze badges

    answered May 2, 2012 at 9:32

    eumiro's user avatar

    eumiroeumiro

    205k34 gold badges297 silver badges261 bronze badges

    5

    Just another idea:

    >>> bin(6)[2:].zfill(8)
    '00000110'
    

    Shorter way via string interpolation (Python 3.6+):

    >>> f'{6:08b}'
    '00000110'
    

    answered May 2, 2012 at 9:37

    mshsayem's user avatar

    mshsayemmshsayem

    17.5k11 gold badges59 silver badges68 bronze badges

    3

    A bit twiddling method…

    >>> bin8 = lambda x : ''.join(reversed( [str((x >> i) & 1) for i in range(8)] ) )
    >>> bin8(6)
    '00000110'
    >>> bin8(-3)
    '11111101'
    

    marbel82's user avatar

    marbel82

    9151 gold badge18 silver badges39 bronze badges

    answered May 2, 2012 at 10:07

    sobel's user avatar

    sobelsobel

    6435 silver badges8 bronze badges

    4

    Just use the format function

    format(6, "08b")
    

    The general form is

    format(<the_integer>, "<0><width_of_string><format_specifier>")
    

    answered Apr 7, 2016 at 20:16

    theOne's user avatar

    theOnetheOne

    4114 silver badges4 bronze badges

    1

    eumiro’s answer is better, however I’m just posting this for variety:

    >>> "%08d" % int(bin(6)[2:])
    00000110
    

    answered May 2, 2012 at 9:35

    jedwards's user avatar

    jedwardsjedwards

    29.2k3 gold badges65 silver badges92 bronze badges

    0

    numpy.binary_repr(num, width=None) has a magic width argument

    Relevant examples from the documentation linked above:

    >>> np.binary_repr(3, width=4)
    '0011'
    

    The two’s complement is returned when the input number is negative and width is specified:

    >>> np.binary_repr(-3, width=5)
    '11101'
    

    answered May 1, 2019 at 2:11

    Tom Hale's user avatar

    Tom HaleTom Hale

    39.5k31 gold badges181 silver badges238 bronze badges

    .. or if you’re not sure it should always be 8 digits, you can pass it as a parameter:

    >>> '%0*d' % (8, int(bin(6)[2:]))
    '00000110'
    

    answered May 2, 2012 at 9:47

    thebjorn's user avatar

    thebjornthebjorn

    26k11 gold badges93 silver badges136 bronze badges

    Going Old School always works

    def intoBinary(number):
    binarynumber=""
    if (number!=0):
        while (number>=1):
            if (number %2==0):
                binarynumber=binarynumber+"0"
                number=number/2
            else:
                binarynumber=binarynumber+"1"
                number=(number-1)/2
    
    else:
        binarynumber="0"
    
    return "".join(reversed(binarynumber))
    

    answered Jun 8, 2018 at 16:40

    Shadrack Kimutai's user avatar

    4

    The best way is to specify the format.

    format(a, 'b')
    

    returns the binary value of a in string format.

    To convert a binary string back to integer, use
    int() function.

    int('110', 2)
    

    returns integer value of binary string.

    answered Apr 27, 2020 at 3:18

    Pranjalya's user avatar

    PranjalyaPranjalya

    682 silver badges7 bronze badges

    1

    You can use just:

    "{0:b}".format(n)
    

    In my opinion this is the easiest way!

    answered Aug 11, 2020 at 17:21

    Leha's user avatar

    LehaLeha

    436 bronze badges

    even an easier way

    my_num = 6
    print(f'{my_num:b}')
    

    answered Sep 11, 2020 at 2:33

    Raad Altaie's user avatar

    Raad AltaieRaad Altaie

    9751 gold badge14 silver badges28 bronze badges

    Assuming you want to parse the number of digits used to represent from a variable which is not always constant, a good way will be to use numpy.binary.

    could be useful when you apply binary to power sets

    import numpy as np
    np.binary_repr(6, width=8)
    

    answered Mar 11, 2020 at 13:31

    ama's user avatar

    amaama

    531 silver badge7 bronze badges

    ('0' * 7 + bin(6)[2:])[-8:]
    

    or

    right_side = bin(6)[2:]
    '0' * ( 8 - len( right_side )) + right_side
    

    eyllanesc's user avatar

    eyllanesc

    233k19 gold badges161 silver badges234 bronze badges

    answered Sep 5, 2018 at 0:07

    zerg's user avatar

    1

    def int_to_bin(num, fill):
        bin_result = ''
    
        def int_to_binary(number):
            nonlocal bin_result
            if number > 1:
                int_to_binary(number // 2)
            bin_result = bin_result + str(number % 2)
    
        int_to_binary(num)
        return bin_result.zfill(fill)
    

    answered May 18, 2020 at 9:41

    Dmity Bryuhanov's user avatar

    The python package Binary Fractions has a full implementation of binaries as well as binary fractions. You can do your operation as follows:

    from binary_fractions import Binary
    b = Binary(6) # creates a binary fraction string
    b.lfill(8) # fills to length 8
    

    This package has many other methods for manipulating binary strings with full precision.

    answered Jul 16, 2021 at 14:49

    Jonny Baron's user avatar

    Simple code with recursion:

     def bin(n,number=('')):
       if n==0:
         return(number)
       else:
         number=str(n%2)+number
         n=n//2
         return bin(n,number)
    

    answered Dec 2, 2021 at 22:11

    Mabel137's user avatar

    1

        def convertToBinary(self, n):
            result=""
            if n==0:
                return 0
    
            while n>0:
                r=n%2
                result+=str(r)
                n=int(n/2)
            if n%2==0:
                result+="0"
            return result[::-1]
    

    answered Oct 6, 2022 at 7:50

    neda's user avatar

    nedaneda

    133 bronze badges

    Преобразует целое число в двоичную строку.

    Синтаксис:

    Параметры:

    • x – целое число

    Возвращаемое значение:

    • двоичная строка с префиксом 0b.

    Описание:

    Функция bin() преобразует целое число в двоичную строку с префиксом 0b.

    Результатом будет binary string – двоичная версия заданного целого числа x.

    Примеры преобразований чисел в двоичную систему счисления.

    >>> bin(3)
    # '0b11'
    >>> bin(-10)
    # '-0b1010'
    

    Если префикс 0b является НЕ желательным , вы можете использовать любой из следующих способов.

    >>> format(14, '#b'), format(14, 'b')
    # ('0b1110', '1110')
    >>> f'{14:#b}', f'{14:b}'
    # ('0b1110', '1110')
    

    Смотрите также встроенную функцию format().

    Время чтения 3 мин.

    Существуют ли какие-либо методы Python для преобразования Integer(или Long) в двоичную строку? Да, существуют три метода, которые вы можете использовать для преобразования int в двоичную строку в Python.

    В байте 8 бит. Биты состоят либо из 0, либо из 1. Байт можно интерпретировать по-разному, например, в двоичном восьмеричном или шестнадцатеричном виде. Это, безусловно, показывает, что строку битов можно интерпретировать по-разному.

    Содержание

    1. int в двоичную строку
    2. Преобразование int в binary с помощью bin()
    3. Int в Binary с использованием метода format()
    4. Преобразование с помощью функции str.format()
    5. Заключение

    Чтобы преобразовать целое число (Int) в двоичную строку в Python:

    1. Используйте функцию bin().
    2. Используйте метод format().
    3. Функцию str.format().

    Преобразование int в binary с помощью bin()

    Чтобы преобразовать int в двоичный тип в Python, используйте метод bin(). bin() — это встроенный метод Python, который преобразует десятичный тип данных в двоичный. Функция bin() принимает число в качестве аргумента и возвращает его эквивалентную двоичную строку с префиксом «0b».

    binary = bin(19)

    print(binary)

    Вывод:

    И мы получаем двоичную строку на выходе. bin() является более быстрым методом, чем остальные подходы, поскольку для преобразования в двоичный формат требуется меньше времени.

    Int в Binary с использованием метода format()

    Используя метод bin(), он возвращает вывод с «0b» в качестве префикса. Чтобы удалить префикс «0b» из его вывода, используйте функцию форматирования и отформатируйте вывод.

    format(value, format_spec) — это встроенная функция Python, которая принимает два параметра — value и format_spec и возвращает отформатированный вывод в соответствии с format_spec.

    bindata = format(19, “b”)

    print(bindata)

    Вывод:

    И получаем вывод без «0b» в префиксе.

    Если вам нужно n-битное представление двоичного кода, вы можете использовать лямбда-функцию.

    getbinary = lambda x, n: format(x, ‘b’).zfill(n)

    print(getbinary(11, 21))

    Вывод:

    И мы получаем двоичную строку длиной 21.

    Преобразование с помощью функции str.format()

    string.format() — это встроенный метод Python, который форматирует указанные значения и вставляет их в местозаполнитель строки. Заполнитель определяется с помощью фигурных скобок: { }.

    Метод string.format() допускает множественные замены и форматирование значений. Метод format() принимает значение и формат в качестве аргументов и возвращает отформатированное значение.

    dart = “{0:b}”.format(19)

    print(dart)

    Вывод:

    Позвольте мне объяснить этот пример:

    1. {} помещает переменную в строку.
    2. 0 принимает переменную в позиции аргумента 0.
    3. : добавляет параметры форматирования для этой переменной (иначе она представляла бы десятичную цифру 6).
    4. b преобразует число в его двоичное представление.

    Заключение

    целое число в двоичное в Python

    Преобразование целого числа в двоичное приводит к строке, представляющей целое число по основанию 2. Например, целое число 5 имеет двоичное представление «0b101».

    Мы рассмотрели все три метода преобразования целочисленного значения в двоичную строку и в зависимости от ваших требований, и вы можете использовать один из этих подходов.

    Добавить комментарий