Jun-04-2024, 06:09 AM
(This post was last modified: Jun-04-2024, 06:09 AM by Gribouillis.)
(Jun-04-2024, 03:43 AM)Curbie Wrote: does that denote an initialize string of bytes or something else?Yes the b in front of a literal string denotes a string of bytes
"ABC" # this is a string of unicode characters (type str) 'ABC' # this is also a string of unicode characters (type str) b'ABC' # this is a string of bytes (type bytes)A string of bytes behaves like a read-only array of 8 bits integers
>>> list( b'tom' ) [116, 111, 109] >>> "tom".encode('ascii') b'tom' >>> b'tom'.decode('ascii') 'tom' >>>
(Jun-04-2024, 03:43 AM)Curbie Wrote: because I don’t learn anything, which was the point of my post.Your main problem will be the time it takes to get familiar with Python's libraries. In this case I want to use the
bytes.translate()
method because then I don't have to iterate through the bytes of the string (more precisely the iteration is done by the underlying C implementation of Python), so I first create a 256 bytes translation table that I need to use this function.Here is a version of unpack()
rev_table = r50 + b'\xff' * (256 - 40) def unpack(n): if 0 <= n < 64000: a, c = divmod(n, 40) a, b = divmod(a, 40) return bytes((a, b, c)).translate(rev_table) raise ValueError(n)In Python it is better to raise exceptions than to return error codes (because error codes need more ifs for the caller while exceptions propagate by themselves)
« We can solve any problem by introducing an extra level of indirection »