4-byte string to integer
jay.krell at cornell.edu
jay.krell at cornell.edu
Wed Oct 4 12:06:14 EDT 2000
Here's one *extremely ineffiicient* piece of code I was using a while ago:
def Reverse(s):
# This works for any sequence type;
# it returns a new sequence / inefficient / recursive
if (len(s) < 1):
return s
else:
return s[len(s) - 1:] + Reverse(s[:len(s) - 1])
def unpack(bytes, offset = 0, size = -1):
# little endian integer from string, very inefficiently
if size == -1:
size = len(bytes)
return reduce(
lambda resultSoFar, next: (resultSoFar << 8) | (0xff & ord(next)),
Reverse(bytes[offset : offset + size]),
0
)
at the time Python had no unicode support and it seemed pretty broken that
The way to do binary i/o was to read stuff into strings, not arrays of bytes
(or did I misunderstand something?).
It's from http://home.netcom.com/~jaykrell/1Pecoff.py that reads in a just
little information about Win32 "pe/coff" files..till I got sick of Python..
(the code is doing file type detection, it is not based on filename
extension;
the pretty print is pleasantly data driven using Python's
__class__/__name__/__dict__ features)
Z:\dev\Jk\src\imp3>1pecoff.py \msdev5\vc\lib\kernel32.lib
Library
(
)
Z:\dev\Jk\src\imp3>1pecoff.py Z:\msdev5\vc\lib\BINMODE.OBJ
Object
(
)
Z:\dev\Jk\src\imp3>1pecoff.py Z:\msdev5\vc\bin\LIB.EXE
Executable
(
msdosStub = string(...)
header = Header
(
numberOfSymbols = int(0)
sizeOfOptionalHeader = int(224)
characteristics = int(271)
numberOfSections = int(5)
filePointerToSymbolTable = int(0)
timeDateStamp = int(853994404)
machine = int(332)
)
peOffset = int(128)
)
It even includes a little "struct" package (about seven lines) since the
standard Python stuff does not enable specifying exact offets and sizes like
I needed.
For big endian, remove the "Reverse" call.
..Jay
-----Original Message-----
From: j vickroy <jim.vickroy at noaa.gov>
Newsgroups: comp.lang.python
To: python-list at python.org <python-list at python.org>
Date: Wednesday, October 04, 2000 8:38 AM
Subject: 4-byte string to integer
>How can a 4-byte string be converted to an unsigned integer using
>Python?
>
>The byte order may be either big or little endian.
>
>Thnaks
>--
>http://www.python.org/mailman/listinfo/python-list
More information about the Python-list
mailing list