Use bitshifting and addition:

bytes = b"\x00\x00\x02\x01"
i = 0
for b in bytes:
    i <<= 7
    i += b     # Or use (b & 0x7f) if the last bit might not be zero.
print(i)

Result:

257
Answer from Mark Byers on Stack Overflow
🌐
Programiz
programiz.com › python-programming › methods › built-in › bytes
Python bytes()
# convert string to bytes byte_message = bytes(message, 'utf-8') print(byte_message) # Output: b'Python is fun' ... bytes() method returns a bytes object which is an immutable (cannot be modified) sequence of integers in the range 0 <=x < 256. If you want to use the mutable version, use the ...
🌐
Real Python
realpython.com › python-bytes
Bytes Objects: Handling Binary Data in Python – Real Python
March 5, 2025 - To work around this limitation, you can choose from many options. Arguably, the most straightforward way to use two’s complement when reading or writing binary data in Python is to call an integer’s .to_bytes() and .from_bytes() methods with the signed parameter set to True:
Discussions

Working with bytes and binary data in Python - Stack Overflow
Four consecutive bytes in a byte string together specify some value. However, only 7 bits in each byte are used; the most significant bit is always zero and therefore its ignored (that makes 28 bits More on stackoverflow.com
🌐 stackoverflow.com
working with bytes in python - Stack Overflow
In the original code, you do a ... two byte values into a single numeric value. In Python, there is built-in functionality for this: use the struct module. As it turns out, this module is already built for reading several values at a time. Also, use forward slashes for file names - it's easier, and guaranteed to work. Use a with-block to ensure ... More on stackoverflow.com
🌐 stackoverflow.com
Working with the email library and parsing bytes types
No one can help me? More on reddit.com
🌐 r/learnpython
1
May 21, 2018
How to read CSV file from memory ?

You could try just reading the file and creating a StringIO object:

import StringIO

csv_fo = StringIO.StringIO(request.FILES['csv_file'].read())
file_content = extract_data(csv_fo)
More on reddit.com
🌐 r/django
6
5
September 18, 2014
🌐
W3Schools
w3schools.com › python › ref_func_bytes.asp
Python bytes() Function
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training ... The bytes() function returns a bytes object.
🌐
w3resource
w3resource.com › python › python-bytes.php
Python Bytes, Bytearray
>>> x = "Python String" >>> y = b"Python String" >>> print(x) Python String >>> print(y) b'Python String' >>> # Found in unicode representation of characters but not in ascii >>> x = "Python" >>> y = bytes("Python", "utf8") >>> print(x) Python >>> print(y) b'Python' >>> PREV : Python break, continue NEXT : Python String · Test your Python skills with w3resource's quiz 
🌐
Mimo
mimo.org › glossary › python › bytes
Python Bytes: Syntax, Usage, and Examples
The bytes() constructor can also take a sequence of integers or even tuples with numbers from 0 to 255. The return value will always be a bytes class object. One of the most common operations is converting a string to a bytes object: ... This process is essential when sending data over a network or storing data in binary files. The opposite of this operation—bytes to string—requires decoding. If you skip specifying the encoding, Python 3 uses UTF-8 as the default encoding, which works for most unicode characters.
Top answer
1 of 2
7

Use bitshifting and addition:

bytes = b"\x00\x00\x02\x01"
i = 0
for b in bytes:
    i <<= 7
    i += b     # Or use (b & 0x7f) if the last bit might not be zero.
print(i)

Result:

257
2 of 2
1

Using the bitarray module, you can do it a lot quicker for big numbers:

Benchmarks (factor 2.4x speedup!):

janus@Zeus /tmp % python3 -m timeit -s "import tst" "tst.tst(10000)" 
10 loops, best of 3: 251 msec per loop
janus@Zeus /tmp % python3 -m timeit -s "import tst" "tst.tst(100)"  
1000 loops, best of 3: 700 usec per loop
janus@Zeus /tmp % python3 -m timeit -s "import sevenbittoint, os" "sevenbittoint.sevenbittoint(os.urandom(10000))"
10 loops, best of 3: 73.7 msec per loop
janus@Zeus /tmp % python3 -m timeit -s "import quick, os" "quick.quick(os.urandom(10000))"                        
10 loops, best of 3: 179 msec per loop

quick.py (from Mark Byers):

def quick(bites):
  i = 0
  for b in bites:
    i <<= 7
    i += (b & 0x7f)
    #i += b
  return i

sevenbittoint.py:

import bitarray
import functools

def inttobitarray(x):
  a = bitarray.bitarray()
  a.frombytes(x.to_bytes(1,'big'))
  return a

def concatter(accumulator,thisitem):
  thisitem.pop(0)
  for i in thisitem.tolist():
    accumulator.append(i)
  return accumulator

def sevenbittoint(bajts):
  concatted = functools.reduce(concatter, map(inttobitarray, bajts), bitarray.bitarray())
  missingbits = 8 - len(concatted) % 8
  for i in range(missingbits): concatted.insert(0,0) # zeropad
  return int.from_bytes(concatted.tobytes(), byteorder='big')

def tst():
  num = 32768
  print(bin(num))
  print(sevenbittoint(num.to_bytes(2,'big')))

if __name__ == "__main__":
  tst()

tst.py:

import os
import quick
import sevenbittoint

def tst(sz):
    bajts = os.urandom(sz)
  #for i in range(pow(2,16)):
  #  if i % pow(2,12) == 0: print(i)
  #  bajts = i.to_bytes(2, 'big')
    a = quick.quick(bajts)
    b = sevenbittoint.sevenbittoint(bajts)
    if a != b: raise Exception((i, bin(int.from_bytes(bajts,'big')), a, b))
🌐
Agr0 Hacks Stuff
agrohacksstuff.io › posts › working-with-bytecode-in-python
Working with Bytecode in Python | Agr0 Hacks Stuff
April 5, 2024 - Or you can completely zero out all or a portion of a byte by AND’ing it with all zeroes. You can use a logical OR to flip something to all ones, or copy similar to the AND function. AKA eXclusive OR. This is generally useful in things like Assembly when you need to zero out a register or something, but hey it works in python in a pinch.
Find elsewhere
🌐
iO Flood
ioflood.com › blog › python-bytes
Python Bytes Data Type | bytes() Function Guide
February 6, 2024 - Let’s discuss these problems and their solutions to help you navigate through your Python bytes journey smoothly. One common issue when working with bytes is the UnicodeDecodeError. This occurs when you try to decode a bytes object that contains non-ASCII characters using the ASCII encoding.
🌐
Python
docs.python.org › 3 › c-api › bytes.html
Bytes Objects — Python 3.14.8 documentation
Take a C printf()-style format string and a variable number of arguments, calculate the size of the resulting Python bytes object and return a bytes object with the values formatted into it.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-bytes-method
Python bytes() method - GeeksforGeeks
July 11, 2025 - By passing a single integer to bytes(), Python will create a bytes object of that length, filled with zero values (because a byte is initially 0).
🌐
Python
docs.python.org › 3.1 › library › stdtypes.html
5. Built-in Types — Python v3.1.5 documentation
Bytes and bytearray objects contain single bytes – the former is immutable while the latter is a mutable sequence. Bytes objects can be constructed the constructor, bytes(), and from literals; use a b prefix with normal string syntax: b'xyzzy'. To construct byte arrays, use the bytearray() ...
🌐
Real Python
realpython.com › lessons › operations-bytes-objects
Operations on bytes Objects (Video) – Real Python
01:37 If you were to take something like a—and you’ve practiced this earlier, but does slicing work, and indexing? Yes. What’s a little different, though, is that it is showing the byte value. In this case, the letter is 'c' but the index will show the ASCII value. Index 1 for 'b' would be 98. 01:54 But what’s kind of interesting is if you were to create a slice, say from 2 to 4, it does show the letters and returns a byte string. And just for practice, make another slice that goes from 1 up to 5. 02:10 As far as built-in Python functions, if you look again at the bytes object that you’ve created, len() returns the number of items in a container.
Published: October 1, 2019
🌐
CodeRivers
coderivers.org › blog › bytes-python
Working with Bytes in Python: A Comprehensive Guide - CodeRivers
February 22, 2026 - In the second case, we create a bytes object of length 5, filled with the byte value x. Elements in a bytes object can be accessed like elements in a list or tuple. Each element is an integer representing the byte value. b = b'hello' print(b[0]) # Access the first byte, which will print the ASCII value of 'h' (104) Slicing works the same way as it does for strings and other sequences in Python.
🌐
PythonForBeginners.com
pythonforbeginners.com › home › bytes in python
Bytes in Python - PythonForBeginners.com
July 5, 2021 - Byte objects contain data that are machine-readable and we can store a byte object directly into secondary storage. In python, we can explicitly create byte objects from other data such as lists, strings etc.
🌐
Python Guides
pythonguides.com › python-bytes-function
Python bytes() Function
3 weeks ago - The Python bytes() function becomes especially useful when your automation script writes or reads binary files. A binary file stores raw bytes rather than readable text. Images, PDFs, Excel workbooks, ZIP archives, and audio files are common ...
🌐
Toppr
toppr.com › guides › python-guide › references › methods-and-functions › methods › built-in › bytes › python-bytes
Python bytes() function | Why is Python bytes() function used? |
July 30, 2021 - Python bytes() function is used to convert an object to an immutable (cannot be modified) byte object of the given size and data. The Python bytes() function returns a byte’s object, which is an immutable series of integer numbers ranging from 0 to 256. Python bytes() method is to manipulate ...
🌐
CodeRivers
coderivers.org › blog › how-to-convert-to-byte-in-python
Converting to Byte in Python: A Comprehensive Guide - CodeRivers
February 22, 2026 - However, you can create a new byte object based on the original one with the desired changes. original_byte = b'Hello' new_byte = original_byte[:2] + b'XYZ' + original_byte[2:] print(new_byte) When working with byte objects and strings, encoding and decoding are common operations.
Top answer
1 of 3
5

An idiomatic translation is going to work in a completely different way.

In the original code, you do a bunch of bit-twiddling to convert two byte values into a single numeric value. In Python, there is built-in functionality for this: use the struct module. As it turns out, this module is already built for reading several values at a time.

Also, use forward slashes for file names - it's easier, and guaranteed to work. Use a with-block to ensure that the file is properly closed automatically, and a list comprehension to simplify the looping - stop trying to tell Python how to build a list, and just ask for the list you want.

This gives us:

import struct
with open('C:/Users/CNA/sketchbook/_SRTM/data/N59E010.hgt', 'rb') as data:
    elevation = [
        list(struct.unpack('>1201H', data.read(1201 * 2)))
        for row in range(1201)
    ]
maxheight = max(max(cell for cell in row if cell < 32000) for row in elevation)

and you're done. Welcome to Python :)

2 of 3
2

In Python values like 'hello'[2] are also strings (in this case == 'l'). You need to convert them to integers using ord and back to string using chr.

elevation = [[],[]]
maxheight=0

b = open("C:\\Users\\CNA\\sketchbook\\_SRTM\\data\\N59E010.hgt","rb")
fin = b.read() # you probably need to read more than 1 byte, this will read whole file
print(len(fin))
ix = 0
for row in range(0,1201):
    for col in range(0,1201):
        hi = (ord(fin[ix])   + 0xff) # ord returns unsigned integer, so you probably don't need to convert it
        lo = (ord(fin[ix+1]) + 0xff)
        el = (hi << 8) | lo

See: http://docs.python.org/library/functions.html

🌐
Wikiversity
en.wikiversity.org › wiki › Python_Concepts › Bytes_objects_and_Bytearrays
Python Concepts/Bytes objects and Bytearrays - Wikiversity
January 22, 2025 - One byte is a memory location with a size of 8 bits. A bytes object is an immutable sequence of bytes, conceptually similar to a string · Because each byte must fit into 8 bits, each member x of a bytes object is an unsigned int that satisfies 0≤x≤0b1111_1111
🌐
GeeksforGeeks
geeksforgeeks.org › working-with-binary-data-in-python
Working with Binary Data in Python - GeeksforGeeks
June 22, 2020 - This means that before Python3 we could treat a set of bytes as a string and work from there, this is not the case now, now we have a separate data type, called bytes. This data type can be briefly explained as a string of bytes, which essentially means, once the bytes data type is initialized it is immutable. ... bytestr = bytes(b'abc') # initializing a string with b # makes it a binary string print(bytestr) print(bytestr[0]) bytestr[0] = 97