I had the same problem and I found a simpler and shorter solution.

Here's an example:

Encode:

In [1]: val = 15

In [2]: bin_ = '{0:016b}'.format(val)
In [3]: bin_
Out[3]: '0000000000001111'

Or:

In [4]: bin_ = bin(val)[2:].zfill(16)
In [5]: bin_
Out[5]: '0000000000001111'

Decode:

In [6]: int(bin_, 2)
Out[6]: 15
Answer from Benyamin Jafari on Stack Overflow
Top answer
1 of 2
11

I had the same problem and I found a simpler and shorter solution.

Here's an example:

Encode:

In [1]: val = 15

In [2]: bin_ = '{0:016b}'.format(val)
In [3]: bin_
Out[3]: '0000000000001111'

Or:

In [4]: bin_ = bin(val)[2:].zfill(16)
In [5]: bin_
Out[5]: '0000000000001111'

Decode:

In [6]: int(bin_, 2)
Out[6]: 15
2 of 2
1

This isn't a very popular question to answer, I can see, so I'll put this up in the meantime:

def convert_to_binary(value):
    '''
    Converts a float to a 16-bit binary string.
    '''
    n = ['0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0']
    value = int(value)
    if value > 2**15:
        if value > 2**16:
            print "Value too large"
        else:
            n[0] = '1'
            value = value - (2**15)
    if value > 2**14:
        n[1] = '1'
        value = value - (2**14)
    if value > 2**13:
        n[2] = '1'
        value = value - (2**13)
    if value > 2**12:
        n[3] = '1'
        value = value - (2**12)
    if value > 2**11:
        n[4] = '1'
        value = value - (2**11)
    if value > 2**10:
        n[5] = '1'
        value = value - (2**10)
    if value > 2**9:
        n[6] = '1'
        value = value - (2**9)
    if value > 2**8:
        n[7] = '1'
        value = value - (2**8)
    if value > 2**7:
        n[8] = '1'
        value = value - (2**7)
    if value > 2**6:
        n[9] = '1'
        value = value - (2**6)
    if value > 2**5:
        n[10] = '1'
        value = value - (2**5)
    if value > 2**4:
        n[11] = '1'
        value = value - (2**4)
    if value > 2**3:
        n[12] = '1'
        value = value - (2**3)
    if value > 2**2:
        n[13] = '1'
        value = value - (2**2)
    if value > 2**1:
        n[14] = '1'
        value = value - (2**1)
    if value >= 2**0:
        n[15] = '1'
        value = value - (2**0)

        n = ''.join(n)
        n = str(n)

        print str(n)
        return str(n)

def convert_back(bin_num):
    """
    Converts binary string to a float.
    """
    value = 0
    print type(bin_num)
    n = list(bin_num)

    if n[0] == '1':
        value = value + (2 ** 15)
    if n[1] == '1':
        value = value + (2 ** 14)
    if n[2] == '1':
        value = value + (2 ** 13)
    if n[3] == '1':
        value = value + (2 ** 12)
    if n[4] == '1':
        value = value + (2 ** 11)
    if n[5] == '1':
        value = value + (2 ** 10)
    if n[6] == '1':
        value = value + (2 ** 9)
    if n[7] == '1':
        value = value + (2 ** 8)
    if n[8] == '1':
        value = value + (2 ** 7)
    if n[9] == '1':
        value = value + (2 ** 6)
    if n[10] == '1':
        value = value + (2 ** 5)
    if n[11] == '1':
        value = value + (2 ** 4)
    if n[12] == '1':
        value = value + (2 ** 3)
    if n[13] == '1':
        value = value + (2 ** 2)
    if n[14] == '1':
        value = value + (2 ** 1)
    if n[15] == '1':
        value = value + (2 ** 0)

    print value

    return value
🌐
GitHub
gist.github.com › 711360947b40e8cc404e
Convert int to 16 bits in python · GitHub
Convert int to 16 bits in python · Raw · convert_16bits.py · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Reddit
reddit.com › r/learnpython › converting integer to 16-bit hexadecimal in big-endain form
r/learnpython on Reddit: Converting integer to 16-bit hexadecimal in Big-endain form
March 6, 2014 -

I'm trying to take a number (such as -200) and send it to a robot. The number must be converted to big-endian and sent in two bytes. WolframAlpha does this (the result I need to send is 38ff) but I haven't found a way to do this in python.

🌐
Reddit
reddit.com › r/learnpython › bit operations with python: saving an integer into 16 bit
r/learnpython on Reddit: Bit operations with Python: Saving an integer into 16 bit
February 8, 2019 - Use struct.pack, it has the common formats like B for unsigned char (8 bits) and H for unsigned char (16 bits). Note that you can provide multiple values at once ... Thanks, this really helped!! As I need to merge content 2 and 3 into one byte, would this make sence?
🌐
Mkyong
mkyong.com › home › python › python – how to convert int to a binary string?
Python – How to convert int to a binary string? | mkyong.com
June 2, 2020 - In Python, we can use bin() or format() to convert an integer into a binary string representation. print(bin(1)) # 0b1 print(bin(-1)) # -0b1 print(bin(10)) # 0b1010 print(bin(-10)) # -0b1010 print("{0:b}".format(10)) # 1010 print("{0:#b}".f...
🌐
Stack Overflow
stackoverflow.com › questions › 50032976 › int2-to-16-bit-conversion-python
binary - Int(2) to 16 bit conversion python - Stack Overflow
Anyway, most things that say they want "16 bits binary" don't want a string of 16 1 and 0 bytes; they want two bytes. You probably want something like value.to_bytes(2, 'big', signed=True) or some other combination of the flags (or struct.pack('>h', value) or some other combination of struct flags, if you need Python 2 compatibility). ... The documentation describes it as a 2 byte integer.
Find elsewhere
🌐
Python
wiki.python.org › moin › BitManipulation
BitManipulation - Python Wiki
"Integers (int) These represent numbers in an unlimited range, subject to available (virtual) memory only. For the purpose of shift and mask operations, a binary representation is assumed, and negative numbers are represented in a variant of 2’s complement which gives the illusion of an infinite string of sign bits extending to the left."
🌐
Quora
quora.com › How-can-I-compress-a-16-bit-integer-to-an-8-bit-size-integer-in-Python
How to compress a 16-bit integer to an 8-bit size integer in Python - Quora
If possible, how can this be done using Python? · · If the numbers are small enough to fit in 8 bits it is possible. But 16 bits can hold up to 32767 and down to -32768. 8 bits can hold up ton127 and down to -128. So if the integers are signed, and all of them hold values less than 127 and greater than -128, then you can chop off the top 8 bits and not lose any information. In general compressing to 50% is very difficult and usually does not work for arbitrary binary ...
Top answer
1 of 1
3

This result is even more wild than the first. I know my approach is wrong... but can't work out where i'm wrong.

The problem is in the conversion to bytes. Let's look at it a step at a time:

int(x, 2)

Fine; we treat the string as a base-2 representation of the integer value, and get that integer. Only problem is it's a) unsigned and b) big-endian.

hex(int(x,2))

What this does is create a string representation of the integer, in base 16, with a 0x prefix. Notably, there are two text characters per byte that we want. This is already heading is down the wrong path.

You might have thought of using hexadecimal because you've seen \xAB style escapes inside string representations. This is a completely different thing. The string '\xAB' contains one character. The string '0xAB' contains four.

From there, everything else is still nonsense. Converting to bytes with a text encoding just means that the text character 0 for example is replaced with the byte value 48 (since in UTF-8 it's encoded with a single byte with that value). For this data we get the same results with UTF-8 that we would by assuming plain ASCII (since UTF-8 is "ASCII transparent" and there are no non-ASCII characters in the text).


So how do we do it?

We want to convert the integer from the first step into the bytes used to represent it. Just as there is a .from_bytes class method allowing us to create an integer from underlying bytes, there is an instance method allowing us to get the bytes that would represent the integer.

So, we use .to_bytes, specifying the length, signedness and endianness that was assumed when we created the int from the binary string - that gives us bytes that correspond to that string. Then, we re-create the integer from those bytes, except now specifying the proper signedness and endianness. The reason that .to_bytes makes us specify a length is because the integer doesn't have a particular length - there are a minimum number of bytes required to represent it, but you could use as many more as you like. (This is especially important if you want to handle signed values, since it will do sign-extension automatically.)

Thus:

for i in input_data:
    values = [int(x,2) for x in i]
    as_bytes = [x.to_bytes(2, byteorder='big', signed=False) for x in values]
    reinterpreted = [int.from_bytes(x, byteorder='little', signed=True) for x in as_bytes]
    results_2.append(reinterpreted)

But let's improve the organization of the code a bit. I will first make a function to handle a single integer value, and then we can use comprehensions to process the list. In fact, we can use nested comprehensions for the nested list.

def as_signed_little(binary_str):
    # This time, taking advantage of positional args and default values.
    as_bytes = int(binary_str, 2).to_bytes(2, 'big')
    return int.from_bytes(as_bytes, 'little', signed=True)

# And now we can do:
results_2 = [[as_signed_little(x) for x in i] for i in input_data]
🌐
Delft Stack
delftstack.com › home › howto › python › python int to binary
How to Convert Int to Binary in Python | Delft Stack
February 2, 2024 - In this example, the integer 16 is formatted using the '{0:b}' format specifier, resulting in the binary representation '10000'. Python’s string formatting allows for additional formatting options to customize the output.
🌐
DataCamp
datacamp.com › tutorial › python-data-type-conversion
Python Data Type Conversion: A Guide With Examples | DataCamp
February 16, 2025 - In Python, you can use the hex() function to convert from a decimal value to its corresponding hexadecimal value, or the int() function with base 16 for the hexadecimal number system.
🌐
datagy
datagy.io › home › python posts › python strings › python: int to binary (convert integer to binary string)
Python: Int to Binary (Convert Integer to Binary String) • datagy
December 19, 2022 - 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.
🌐
Python Pool
pythonpool.com › home › tutorials › python int to binary: bin(), format(), and f-strings
Python int to Binary: bin(), format(), and f-strings
July 13, 2026 - Be explicit about the bit width ... 8-bit, 16-bit, 32-bit, or another size. format(value, 'b') returns binary digits without the 0b prefix. You rarely need to write this manually, but the algorithm is useful for learning.
🌐
Note.nkmk.me
note.nkmk.me › home › python
Convert Binary, Octal, Decimal, and Hexadecimal in Python | note.nkmk.me
May 19, 2023 - So, if you want the binary string in two's complement form, use the bitwise-and operator (&) with the maximum number required for your digit size. For example, use 0b1111 (= 0xf) for 4-bit, 0xff for 8-bit, and 0xffff for 16-bit representations.
🌐
GeeksforGeeks
geeksforgeeks.org › python-program-to-covert-decimal-to-binary-number
Convert Decimal to Binary Number - GeeksforGeeks
Given a binary number, the task ... number into an equivalent hexadecimal number. i.e convert the number with base value 2 to base value 16. In hexadecimal representation we 16 values to represent a number. Numbers 0-9 are expressed by digits 0-9 ... The task of converting a floating-point number to its binary representation in Python involves representing the number in the IEEE 754 format, which consists of a sign bit, an exponent ...
Published: March 19, 2025
🌐
w3resource
w3resource.com › python-exercises › python-basic-exercise-140.php
Python: Convert an integer to binary keep leading zeros - w3resource
May 17, 2025 - Write a Python program to convert an integer to binary that keeps leading zeros. Converting an integer to an n-bit binary number results in its binary representation containing leading zeros up to length n. For example, to convert the integer 5 to a 6-bit binary results in 000101.