(using python 3 here, there are some nomenclature differences in 2)

Well first, you could just leave everything as bytes. This is perfectly valid:

reg_val_msb, reg_val_lsb = struct.pack('<H', 0xABCD)

bytes allows for "tuple unpacking" (not related to struct.unpack, tuple unpacking is used all over python). And bytes is an array of bytes, which can be accessed via index as you wanted.

b = struct.pack('<H',0xABCD)

b[0],b[1]
Out[52]: (205, 171)

If you truly wanted to get it into an array.array('B'), it's still rather easy:

ary = array('B',struct.pack('<H',0xABCD))
# ary = array('B', [205, 171])

print("0x%X" % ary[0])
# 0xCD
Answer from roippi on Stack Overflow
🌐
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 - For Content 4: How can I store the value 17 in 16bits? Do I need to shift? Do I need to use ctypes uint16? I am happy about any help! ... For content 1: the value of 250 automatically leads to 8 bit. Do I still need to use bytes([250]) to get a byte that I can then store into the bytearray and then send it via UDP? What does bytes() actually do? Integers are variable sized in Python, so even though your value can be stored in an unsigned byte, it isn't actually doing this automatically.
Discussions

cryptography - Python convert integer to 16-byte bytes - Stack Overflow
I'm trying to use AES-CTR-128 in my code. I use Python 2.7 and utilize the cryptography module to do the encryption. I need to set specific Counter value, for example counter_iv = 112. When I tri... More on stackoverflow.com
🌐 stackoverflow.com
python - Represent number as a bytes using 16-bit blocks - Stack Overflow
I wish to convert a number like 683550 (0xA6E1E) to b'\x1e\x6e\x0a\x00', where the number of bytes in the array is a multiple of 2 and where the len of the bytes object is only so long as it needs ... More on stackoverflow.com
🌐 stackoverflow.com
python - 16 bit Binary conversion - Stack Overflow
I have found several ways to convert both Integer and Float values to binary, and they each have their issues. I need to take an Integer/Float input between values of 0 and 10,000, convert to a 16-... More on stackoverflow.com
🌐 stackoverflow.com
string - Convert 16 bytes of random data to integer in Python - Stack Overflow
I have generated a random 16 byte string. It looks like this: b'\xb68 \xe9L\xbd\x97\xe0\xd6Q\x91c\t\xc3z\\' I want to convert this to a (positive) integer. What's the best way to do this in Python... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-convert-int-to-bytes-in-python
How to Convert Int to Bytes in Python? - GeeksforGeeks
July 23, 2025 - .to_bytes() method is the most direct way to convert an integer to bytes. It allows specifying the byte length and byte order (big for big-endian, little for little-endian). ... Explanation: Here, 2 ensures a fixed 2-byte representation, adding ...
🌐
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.
Top answer
1 of 2
5

First do you have a good reason to use the low level hazardous material instead of the higher level API? This level is intended to be used only through the high level API of for special purposes.

Next, you are misleading any further reader by writing modes.CTR(counter_iv), because the counter mode does not use an initialization vector but a nonce according to its documentation. And the error you get is normal, since the doc states the nonce shall be a byte string of same size of the cipher block so for AES it must be 128 bits or 16 bytes.

BTW the doc also states that a nonce should never be reused

... It is critical to never reuse a nonce with a given key. Any reuse of a nonce with the same key compromises the security of every message encrypted with that key.

Nayuki's answer explain how to build a 16 bytes string from your int, but be sure to correctly use cryptography if you use the low level hazardous material

2 of 2
3

In Python 2, you can convert an integer to a byte string in little endian like this:

counter_iv = 112  # This can be a pretty big number
iv_bytes = "".join(chr((counter_iv >> (i * 8)) & 0xFF) for i in range(16))

Expanding the code to explain:

counter_iv = 112  # Can be from 0 to 3.40e38
temp = []  # Will be an array of bytes
for i in range(16):
    # Get the i'th byte counting from the least significant end
    b = (counter_iv >> (i * 8)) & 0xFF
    temp.append(b)
# For example, temp == [0x70, 0x00, ... 0x00]

# Will be an array of 1-character strings
temp2 = [chr(b) for b in temp]
# For example, temp2 == ['\x70', '\x00', ..., '\x00']

# Concatenate all the above together
iv_bytes = "".join(temp2)
# For example, iv_bytes == '\0x70\0x00...\0x00'
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
Find elsewhere
🌐
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.

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]
🌐
Python
wiki.python.org › moin › BitManipulation
BitManipulation - Python Wiki
Here is some information and goals related to Python bit manipulation, binary manipulation. ... Turn "11011000111101..." into bytes, (padded left or right, 0 or 1,) and vice versa.
🌐
Quora
quora.com › How-can-integers-be-converted-into-bytes-or-vice-versa-using-Python
How can integers be converted into bytes (or vice versa) using Python? - Quora
Answer: First of all, Python does not have an explicit byte data type, just int for all storing any integer. If you insist on retrieving the least significant 8 bits of an int you simply and the int with 255, as in integer&255 to get rid of all the other bits. Note that the result still is an int...
🌐
Delft Stack
delftstack.com › home › howto › python › how to convert bytes to integers
How to Convert Bytes to Int in Python 2.7 and 3.x | Delft Stack
February 2, 2024 - One byte has 8 bits; that’s why its maximum value is 0xFF. In some circumstances, you need to convert bytes or bytes array to integers for further data processing. This short article introduces methods to convert byte to int in Python, like the struct.unpack method in Python 2.7 and int.from_bytes() in Python 3.x.
🌐
Raspberry Pi
raspberrypi.org › board index › programming › python
how to convert an integer to byte(s) in python? - Raspberry Pi Forums
November 16, 2017 - In Python3 ints have a function to_bytes(length, byteorder, signed=False) that returns an array of bytes (a byte string) of a given length in the given byte order where 'big' means most significant byte first and 'little' means least significant byte first, and whether it is a signed integer ...
🌐
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
As Tony Flury points out, though, ... to do in Python - you would be better off trying it in C, which is well suited to working with bits at a low level. Is it worth doing? For one single number, it isn’t - you would save 8 bits, and probably use up several hundred bytes (at least) on the compression code, even using C. If you had a large number of small values it might be worth doing. ... Compressing a 16-bit signed or unsigned integer into 8 bits ...
🌐
Bobby Hadz
bobbyhadz.com › blog › convert-int-to-bytes-in-python
How to convert Int to Bytes and Bytes to Int in Python | bobbyhadz
Use the `int.to_bytes()` method to convert an integer to bytes in Python. The method returns an array of bytes representing an integer.
🌐
GitHub
github.com › bobbyhadz › convert-int-to-bytes-in-python › blob › main › main.py
convert-int-to-bytes-in-python/main.py at main · bobbyhadz/convert-int-to-bytes-in-python
A repository for an article at https://bobbyhadz.com/blog/convert-int-to-bytes-in-python - bobbyhadz/convert-int-to-bytes-in-python
Author: bobbyhadz