Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk3 min

Convert an Integer to Bytes in Python

Use Python’s int.to_bytes() to encode an integer as bytes, with the width, byte order, and signedness required by your format.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Python’s int.to_bytes() method, choosing a byte length and byte order that match the format you need. For example, 1024.to_bytes is not valid syntax because the value must be parenthesized; write (1024).to_bytes(2, byteorder="big") to get b"x04x00". The result is a bytes object.

Convert an integer with int.to_bytes()

The method signature is n.to_bytes(length, byteorder, signed=False). The length sets the output width in bytes, and byteorder must be "big" or "little". The default for signed is False, so values are treated as unsigned unless you request signed encoding. See Python’s int.to_bytes() documentation.

n = 1024
encoded = n.to_bytes(2, byteorder="big")
print(encoded)  # b"x04x00"

Choose the width and order required by the receiving file format or protocol. Python raises OverflowError when the integer cannot be represented in the specified number of bytes.

Choose the byte length

If you need the smallest unsigned representation of a nonnegative integer, calculate its width from its bit length:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
n = 1024
length = (n.bit_length() + 7) // 8
encoded = n.to_bytes(length, byteorder="big")

This produces a compact representation, but it may not match a format that requires a fixed-width field. For example, a protocol may require two bytes even when the value could fit in one; the extra leading zero byte is part of that representation.

Zero has a bit length of zero, so the formula gives a zero-byte result. If your format requires at least one byte, use:

length = max(1, (n.bit_length() + 7) // 8)

Choose big-endian or little-endian

Byte order determines which end of the value is stored first. Big-endian places the most significant byte first; little-endian places it last. For the same value and width, the byte sequence differs:

n = 1000
big = n.to_bytes(2, byteorder="big")
little = n.to_bytes(2, byteorder="little")

print(big)     # b"x03xe8"
print(little)  # b"xe8x03"

Use the order specified by the format you are reading or writing. sys.byteorder is appropriate only when you specifically need the current machine’s native order; it is not a substitute for a fixed byte order in data exchanged between systems.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Encode negative integers

Negative values cannot be represented in the default unsigned mode. Set signed=True to use two’s-complement encoding and choose a width large enough for the value:

encoded = (-1024).to_bytes(2, byteorder="big", signed=True)
print(encoded)  # b"xfcx00"

The signed setting affects positive values too: the same high-bit pattern can be interpreted differently depending on whether decoding is signed or unsigned. Keep the width and signedness aligned with the format.

Decode the bytes and check a round trip

Use int.from_bytes() to turn a bytes-like value back into an integer. Supply the same byte order and signedness used for the encoding:

n = 1000
raw = n.to_bytes(2, byteorder="little")
restored = int.from_bytes(raw, byteorder="little")

print(restored)  # 1000

For signed values, pass signed=True to int.from_bytes() as well. The decoder also accepts a bytes-like object or an iterable that yields byte values. See Python’s int.from_bytes() documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Know the Python version behavior

int.to_bytes() and int.from_bytes() have been available since Python 3.2. Python 3.11 added defaults that let to_bytes() omit its length and byte order, and let from_bytes() omit its byte order. The no-argument form of to_bytes() is a one-byte shorthand: (65).to_bytes() returns b"A", but values above 255 raise OverflowError. For code that must also run on Python 3.10 or earlier, provide the required arguments explicitly.

Quick checks when conversion fails or looks wrong

  • If you see OverflowError, check that the selected width can represent the value and that a negative value is encoded with signed=True.
  • If the bytes appear reversed, verify whether the format expects "big" or "little".
  • If a decoded integer is wrong, check that decoding uses the encoding’s byte order, width, and signedness.
  • If a leading zero byte is missing, use the fixed width required by the destination format instead of the minimum computed width.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.