Size: 11999
Comment:
|
← Revision 30 as of 2024-11-24 18:10:13 ⇥
Size: 12851
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 1: | Line 1: |
I'm looking for information on Python bit manipulation, binary manipulation. It seems that there are no modules for performing Python bit manipulation. I personally want to be able to: |
Here is some information and goals related to Python bit manipulation, binary manipulation. Some tasks include: |
Line 13: | Line 12: |
The closest thing I've found is [[http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/113799|ASPN: bit-field manipulation.]] I imagine that there are many more manipulations people would like to do with bits. |
Relevant libraries include: * [[https://docs.python.org/library/ctypes.html|ctypes — A foreign function library for Python — Python Documentation]] - part of the standard library * [[https://pypi.python.org/pypi/bitarray/|bitarray - efficient arrays of booleans -- C extension]] * [[https://code.google.com/p/python-bitstring/|python-bitstring - A Python module to help you manage your bits. - Google Project Hosting]] * [[https://pypi.python.org/pypi/bitstruct/|bitstruct - This module performs conversions between Python values and C bit field structs represented as Python bytearrays.]] Some simple code is at [[https://code.activestate.com/recipes/113799-bit-field-manipulation/|ActiveState Code Recipes: Bit-field manipulation]] (in Python 2 syntax). Here are some other examples. |
Line 18: | Line 25: |
Line 21: | Line 27: |
{{{ #!python >>> print int('00100001', 2) |
{{{#!python >>> print(int('00100001', 2)) |
Line 26: | Line 31: |
Line 29: | Line 33: |
{{{ #!python >>> print "0x%x" % int('11111111', 2) |
{{{#!python >>> print("0x%x" % int('11111111', 2)) |
Line 33: | Line 36: |
>>> print "0x%x" % int('0110110110', 2) | >>> print("0x%x" % int('0110110110', 2)) |
Line 35: | Line 38: |
>>> print "0x%x" % int('0010101110101100111010101101010111110101010101', 2) | >>> print("0x%x" % int('0010101110101100111010101101010111110101010101', 2)) |
Line 38: | Line 41: |
Line 41: | Line 43: |
{{{ #!python |
{{{#!python |
Line 50: | Line 51: |
Line 53: | Line 53: |
{{{ #!python |
{{{#!python |
Line 62: | Line 61: |
Line 65: | Line 63: |
{{{ #!python |
{{{#!python |
Line 84: | Line 81: |
Line 86: | Line 82: |
Line 88: | Line 83: |
Line 94: | Line 90: |
Line 102: | Line 99: |
The simplest approach is to use the int type with the ``base`` argument. {{{ #!python |
Use the int type with the base argument: {{{#!python |
Line 112: | Line 108: |
Another approach to decyphering "0xdecafbad" style hex strings, is to use eval: {{{ #!python >>> eval("0xdecafbad ") 3737844653L }}} However, this could be dangerous, depending on where you're getting your data from. Here's a function that is safer: {{{ #!python def hex_to_integer(h): """Convert a hex string to an integer. The hex string can be any length. It can start with an 0x, or not. Unrecognized characters will raise a ValueError. This function released into the public domain by it's author, Lion Kimbro. """ num = 0 # Resulting integer h = h.lower() # Hex string if h[:2] == "0x": h = h[2:] for c in h: # Hex character num *= 16 if "0" <= c <= "9": num += ord(c) - ord("0") elif "a" <= c <= "f": num += ord(c) - ord("a") + 10 else: raise ValueError(c) return num }}} |
Do not use alternatives that utilize eval. eval will execute code passed to it and can thus compromise the security of your program. |
Line 153: | Line 110: |
Line 156: | Line 112: |
{{{ #!python |
{{{#!python |
Line 159: | Line 114: |
s='' t={'0':'000','1':'001','2':'010','3':'011', |
s='' t={'0':'000','1':'001','2':'010','3':'011', |
Line 162: | Line 117: |
for c in oct(a)[1:]: s+=t[c] return s }}} |
for c in oct(a)[1:]: s+=t[c] return s }}} |
Line 169: | Line 123: |
{{{ #!python |
{{{#!python |
Line 174: | Line 127: |
Line 176: | Line 128: |
Line 179: | Line 130: |
"Integers (int) These represent numbers in an unlimited range, subject to available (virtual) memory only. For the purpose of shift and mask operations, a binary representation is assumed, and negative numbers are represented in a variant of 2’s complement which gives the illusion of an infinite string of sign bits extending to the left." | "Integers (int) These represent numbers in an unlimited range, subject to available (virtual) memory only. For the purpose of shift and mask operations, a binary representation is assumed, and negative numbers are represented in a variant of 2’s complement which gives the illusion of an infinite string of sign bits extending to the left." |
Line 189: | Line 140: |
* There is a long discussion on this topic, and why this method is not good, in "Issue 3439" at Python.org: http://bugs.python.org/issue3439 This discussion led up to the addition of bit_length() in Python 3.1. {{{#!Python |
* There is a long discussion on this topic, and why this method is not good, in "Issue 3439" at Python.org: http://bugs.python.org/issue3439 This discussion led up to the addition of bit_length() in Python 3.1. {{{#!python |
Line 198: | Line 146: |
}}} |
}}} |
Line 206: | Line 152: |
Line 211: | Line 156: |
{{{#!Python |
{{{#!python |
Line 224: | Line 168: |
}}} |
}}} |
Line 230: | Line 172: |
Line 233: | Line 174: |
{{{#!Python |
{{{#!python |
Line 243: | Line 183: |
}}} |
}}} |
Line 247: | Line 185: |
Line 251: | Line 188: |
Line 254: | Line 190: |
- - - - - - - - - - - - - - - - - - - - - - - - | . - - - - - - - - - - - - - - - - - - - - - - - - |
Line 258: | Line 194: |
{{{#!C |
{{{#!python |
Line 264: | Line 199: |
}}} |
}}} |
Line 273: | Line 206: |
- - - - - - - - - - - - - - - - - - - - - - - - | . - - - - - - - - - - - - - - - - - - - - - - - - |
Line 277: | Line 210: |
This works because each subtraction "borrows" from the lowest 1-bit. For example: {{{#!Python |
This works because each subtraction "borrows" from the lowest 1-bit. For example: {{{#!python |
Line 283: | Line 215: |
# - 1 & 100111 - 1 & 011111 | # - #!python & 100111 - #!python & 011111 |
Line 285: | Line 219: |
}}} |
}}} |
Line 290: | Line 222: |
{{{#!Python |
{{{#!python |
Line 298: | Line 229: |
}}} |
}}} |
Line 302: | Line 231: |
Line 307: | Line 235: |
{{{#!Python |
{{{#!python |
Line 315: | Line 242: |
}}} |
}}} |
Line 319: | Line 244: |
Line 322: | Line 246: |
{{{#!Python |
{{{#!python |
Line 329: | Line 252: |
{{{#!Python |
{{{#!python |
Line 339: | Line 260: |
}}} |
}}} |
Line 343: | Line 262: |
Line 346: | Line 264: |
{{{#!Python |
{{{#!python |
Line 371: | Line 288: |
}}} |
}}} == Bit fields, e.g. for communication protocols == If you need to interpret individual bits in some data, e.g. a byte stream in a communications protocol, you can use the ctypes module. {{{#!python import ctypes c_uint8 = ctypes.c_uint8 class Flags_bits( ctypes.LittleEndianStructure ): _fields_ = [ ("logout", c_uint8, 1 ), # asByte & 1 ("userswitch", c_uint8, 1 ), # asByte & 2 ("suspend", c_uint8, 1 ), # asByte & 4 ("idle", c_uint8, 1 ), # asByte & 8 ] class Flags( ctypes.Union ): _anonymous_ = ("bit",) _fields_ = [ ("bit", Flags_bits ), ("asByte", c_uint8 ) ] flags = Flags() flags.asByte = 0x2 # ->0010 print( "logout: %i" % flags.bit.logout ) # `bit` is defined as anonymous field, so its fields can also be accessed directly: print( "logout: %i" % flags.logout ) print( "userswitch: %i" % flags.userswitch ) print( "suspend : %i" % flags.suspend ) print( "idle : %i" % flags.idle ) }}} {{{#!python >>> logout: 0 logout: 0 userswitch: 1 suspend : 0 idle : 0 }}} |
Line 375: | Line 334: |
Line 377: | Line 335: |
http://graphics.stanford.edu/~seander/bithacks.html | . http://graphics.stanford.edu/~seander/bithacks.html |
Line 380: | Line 339: |
http://webster.cs.ucr.edu/AoA/index.html Volume 4, Chapter 5 "Bit Manipulation" |
. http://webster.cs.ucr.edu/AoA/index.html Volume 4, Chapter 5 "Bit Manipulation" |
Line 384: | Line 343: |
http://www.hackersdelight.org/ | . http://www.hackersdelight.org/ |
Line 386: | Line 347: |
Line 388: | Line 348: |
* [[http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/113799|ASPN: bit-field manipulation]] | * [[https://code.activestate.com/recipes/113799-bit-field-manipulation/]] (in Python 2 syntax). |
Line 391: | Line 352: |
Here is some information and goals related to Python bit manipulation, binary manipulation.
Some tasks include:
- Turn "11011000111101..." into bytes, (padded left or right, 0 or 1,) and vice versa.
- Slice ranges of bits
- Rotate bits, addressed by the bit. That is, say: "rotate bits 13-17, wrapping around the edges," or, "rotate bits 13-17, lose bits on the one side, set all new bits to 0."
- Similarly, revert regions of bits, apply logic to regions of bits, etc.,.
- Switch Endianness, with different block sizes.
- Apply operations in block groupings: ex: apply XOR 10101 (5 bits) repeatedly across a field.
Relevant libraries include:
ctypes — A foreign function library for Python — Python Documentation - part of the standard library
python-bitstring - A Python module to help you manage your bits. - Google Project Hosting
Some simple code is at ActiveState Code Recipes: Bit-field manipulation (in Python 2 syntax).
Here are some other examples.
Manipulations
To integer.
To hex string. Note that you don't need to use x8 bits.
To character. 8 bits max.
Characters to integers, but not to strings of 1's and 0's.
Individual bits.
Transformations Summary
Strings to Integers:
"1011101101": int(str, 2)
"m": ord(str)
"0xdecafbad": int(str, 16) (known to work in Python 2.4)
"decafbad": int(str, 16) (known to work in Python 2.4)
Integers to Strings:
"1011101101": built-in to Python 3 (see below)
"m": chr(str)
"0xdecafbad": hex(val)
"decafbad": "%x" % val
We are still left without a technique for producing binary strings, and decyphering hex strings.
Hex String to Integer
Use the int type with the base argument:
Do not use alternatives that utilize eval. eval will execute code passed to it and can thus compromise the security of your program.
Integer to Bin String
Python 3 supports binary literals (e.g. 0b10011000) and has a bin() function. For older versions:
or better:
Python Integers
From "The Python Language Reference" page on the Data Model:
"Integers (int) These represent numbers in an unlimited range, subject to available (virtual) memory only. For the purpose of shift and mask operations, a binary representation is assumed, and negative numbers are represented in a variant of 2’s complement which gives the illusion of an infinite string of sign bits extending to the left."
Prior to Python 3.1, there was no easy way to determine how Python represented a specific integer internally, i.e. how many bits were used. Python 3.1 adds a bit_length() method to the int type that does exactly that.
Unless you know you are working with numbers that are less than a certain length, for instance numbers from arrays of integers, shifts, rotations, etc. may give unexpected results.
The number of the highest bit set is the highest power of 2 less than or equal to the input integer. This is the same as the exponent of the floating point representation of the integer, and is also called its "integer log base 2".(ref.1)
In versions before 3.1, the easiest way to determine the highest bit set is*:
* There is a long discussion on this topic, and why this method is not good, in "Issue 3439" at Python.org: http://bugs.python.org/issue3439 This discussion led up to the addition of bit_length() in Python 3.1.
An input less than or equal to 0 results in a "ValueError: math domain error"
The section "Finding integer log base 2 of an integer" on the "Bit Twiddling Hacks"(ref.1) web page includes a number of methods for determining this value for integers of known magnitude, presumably when no math coprocessor is available. The only method generally applicable to Python integers of unknown magnitude is the "obvious way" of counting the number of bitwise shift operations needed to reduce the input to 0.
Bit Length Of a Python Integer
bitLen() counts the actual bit length of a Python integer, that is, the number of the highest non-zero bit plus 1. Zero, with no non-zero bit, returns 0. As should be expected from the quote above about "the illusion of an infinite string of sign bits extending to the left," a negative number throws the computer into an infinite loop.
The function can return any result up to the length of the largest integer your computer's memory can hold.
The method using the math module is much faster, especially on huge numbers with hundreds of decimal digits.
bitLenCount()
In common usage, the "bit count" of an integer is the number of set (1) bits, not the bit length of the integer described above. bitLen() can be modified to also provide the count of the number of set bits in the integer. There are faster methods to get the count below.
Operations on Integers of Unknown Magnitude
Some procedures don't need to know the magnitude of an integer to give meaningful results.
bitCount()
The procedure and the information below were found in "Bit Twiddling Hacks"(ref.1)
- - - - - - - - - - - - - - - - - - - - - - - - -
Counting bits set, Brian Kernighan's way*
This method goes through as many iterations as there are set bits. So if we have a 32-bit word with only the high bit set, then it will only go once through the loop.
* The C Programming Language 2nd Ed., Kernighan & Ritchie, 1988.
Don Knuth pointed out that this method was published by Peter Wegner in CACM 3 (1960), 322. Also discovered independently by Derrick Lehmer and published in 1964 in a book edited by Beckenbach.
- - - - - - - - - - - - - - - - - - - - - - - - -
Kernighan and Knuth, potent endorsements!
This works because each subtraction "borrows" from the lowest 1-bit. For example:
It is an excellent technique for Python, since the size of the integer need not be determined beforehand.
parityOf()
From "Bit Twiddling Hacks"
Code almost identical to bitCount(), above, calculates the parity of an integer, returning 0 if there are an even number of set bits, and -1 if there are an odd number. In fact, counting the bits and checking whether the result is odd with bitcount & 1 is about the same speed as the parity function.
lowestSet()
To determine the bit number of the lowest bit set in an integer, in twos-complement notation i & -i zeroes all but the lowest set bit. The bitLen() proceedure then determines its position. Obviously, negative numbers return the same result as their opposite. In this version, an input of 0 returns -1, in effect an error condition.
Single bits
The usual single-bit operations will work on any Python integer. It is up to the programmer to be sure that the value of 'offset' makes sense in the context of the program.
1 # testBit() returns a nonzero result, 2**offset, if the bit at 'offset' is one.
2
3 def testBit(int_type, offset):
4 mask = 1 << offset
5 return(int_type & mask)
6
7 # setBit() returns an integer with the bit at 'offset' set to 1.
8
9 def setBit(int_type, offset):
10 mask = 1 << offset
11 return(int_type | mask)
12
13 # clearBit() returns an integer with the bit at 'offset' cleared.
14
15 def clearBit(int_type, offset):
16 mask = ~(1 << offset)
17 return(int_type & mask)
18
19 # toggleBit() returns an integer with the bit at 'offset' inverted, 0 -> 1 and 1 -> 0.
20
21 def toggleBit(int_type, offset):
22 mask = 1 << offset
23 return(int_type ^ mask)
Bit fields, e.g. for communication protocols
If you need to interpret individual bits in some data, e.g. a byte stream in a communications protocol, you can use the ctypes module.
1 import ctypes
2 c_uint8 = ctypes.c_uint8
3
4 class Flags_bits( ctypes.LittleEndianStructure ):
5 _fields_ = [
6 ("logout", c_uint8, 1 ), # asByte & 1
7 ("userswitch", c_uint8, 1 ), # asByte & 2
8 ("suspend", c_uint8, 1 ), # asByte & 4
9 ("idle", c_uint8, 1 ), # asByte & 8
10 ]
11
12 class Flags( ctypes.Union ):
13 _anonymous_ = ("bit",)
14 _fields_ = [
15 ("bit", Flags_bits ),
16 ("asByte", c_uint8 )
17 ]
18
19 flags = Flags()
20 flags.asByte = 0x2 # ->0010
21
22 print( "logout: %i" % flags.bit.logout )
23 # `bit` is defined as anonymous field, so its fields can also be accessed directly:
24 print( "logout: %i" % flags.logout )
25 print( "userswitch: %i" % flags.userswitch )
26 print( "suspend : %i" % flags.suspend )
27 print( "idle : %i" % flags.idle )
References
ref.1. "Bit Twiddling Hacks" By Sean Eron Anderson
ref.2. "The Art of Assembly Language" by Randall Hyde
http://webster.cs.ucr.edu/AoA/index.html Volume 4, Chapter 5 "Bit Manipulation"
ref.3. Hacker's Delight
Research Links
this is the sort of thing we're looking for:
https://code.activestate.com/recipes/113799-bit-field-manipulation/ (in Python 2 syntax).
related modules:
array module -- (issued with Python)
struct module -- (issued with Python)
binascii module -- (issued with Python)
pySerial module -- access the serial port
see also: BitwiseOperators