# How do I manipulate bits in Python?

In C I could, for example, zero out bit #10 in a 32 bit unsigned value like so:

``````unsigned long value = 0xdeadbeef;
value &= ~(1<<10);
``````

How do I do that in Python ?

Asked by: Elian351 | Posted: 28-01-2022

Bitwise operations on Python ints work much like in C. The `&`, `|` and `^` operators in Python work just like in C. The `~` operator works as for a signed integer in C; that is, `~x` computes `-x-1`.

You have to be somewhat careful with left shifts, since Python integers aren't fixed-width. Use bit masks to obtain the low order bits. For example, to do the equivalent of shift of a 32-bit integer do `(x << 5) & 0xffffffff`.

``````value = 0xdeadbeef
value &= ~(1<<10)
``````

Answered by: Oliver596 | Posted: 01-03-2022

Some common bit operations that might serve as example:

``````def get_bit(value, n):
return ((value >> n & 1) != 0)

def set_bit(value, n):
return value | (1 << n)

def clear_bit(value, n):
return value & ~(1 << n)
``````

Usage e.g.

``````>>> get_bit(5, 2)
True
>>> get_bit(5, 1)
False
>>> set_bit(5, 1)
7
>>> clear_bit(5, 2)
1
>>> clear_bit(7, 2)
3
``````

Answered by: Richard713 | Posted: 01-03-2022

Python has C style bit manipulation operators, so your example is literally the same in Python except without type keywords.

``````value = 0xdeadbeef
value &= ~(1 << 10)
``````

Answered by: Lydia789 | Posted: 01-03-2022

You should also check out BitArray, which is a nice interface for dealing with sequences of bits.

Answered by: Alfred494 | Posted: 01-03-2022

Omit the 'unsigned long', and the semi-colons are not needed either:

``````value = 0xDEADBEEF
value &= ~(1<<10)
print value
"0x%08X" % value
``````

Answered by: Ryan761 | Posted: 01-03-2022

Have you tried copying and pasting your code into the Python REPL to see what will happen?

``````>>> value = 0xdeadbeef
>>> value &= ~(1<<10)
>>> hex (value)
``````

Answered by: Edward454 | Posted: 01-03-2022

If you're going to do a lot of bit manipulation ( and you care much more about readability rather than performance for your application ) then you may want to create an integer wrapper to enable slicing like in Verilog or VHDL:

``` import math
class BitVector:
def __init__(self,val):
self._val = val

def __setslice__(self,highIndx,lowIndx,newVal):
assert math.ceil(math.log(newVal)/math.log(2)) <= (highIndx-lowIndx+1)

# clear out bit slice

self._val = self._val ^ (self._val & clean_mask)
# set new value
self._val = self._val | (newVal<<lowIndx)

def __getslice__(self,highIndx,lowIndx):
return (self._val>>lowIndx)&(2L**(highIndx-lowIndx+1)-1)

b = BitVector(0)
b[3:0]   = 0xD
b[7:4]   = 0xE
b[11:8]  = 0xA
b[15:12] = 0xD

for i in xrange(0,16,4):
print '%X'%b[i+3:i]
```

Outputs:

``` D
E
A
D
```

``````a = int('00001111', 2)
b = int('11110000', 2)
bin(a & b)[2:].zfill(8)
bin(a | b)[2:].zfill(8)
bin(a << 2)[2:].zfill(8)
bin(a >> 2)[2:].zfill(8)
bin(a ^ b)[2:].zfill(8)
int(bin(a | b)[2:].zfill(8), 2)
``````

Answered by: Grace589 | Posted: 01-03-2022

# Similar questions

python - How can I manipulate lists?

In the computer algebra system Sage, I need to multiply a list by 2. I tried the code sage: list = [1, 2, 3]; sage: 2 * list which returns [1, 2, 3, 1, 2, 3] How can I just multiply each element by two?

python - Manipulate table values with PyObjC and Core Data

I recently started programming with xCode and PyObjC and I'm trying to create a logistics application. I have a table with the store's items and a second table with the expenses. Until now everything worked ok by using just the interface builder to link values to core data information and I didn't have to write any code. Now the problem is that I have an attribute "cost" in the expenses table which should not be entered by...

python - Manipulate and print to PDF files in a script

I have several pdf files of some lecture slides. I want to do the following: print every pdf file to another pdf file in which there are 6 slides per page and then merge all the resulting files to one big file while making sure that every original file starts on an odd page number (Edit: obviously, it will be printed in duplex) (possibly adding blank pages when necessary). Is that possible?

python - How to manipulate the following text

I was wondering how to convert text similar to the following: Chapter 3 Convex Functions 97 3.1 Definitions 98 3.2 Basic Properties 103 to: ("Chapter 3 Convex Functions 97" "#97") ("3.1 Definitions 98" "#98") ("3.2 Basic Properties 103" "#103") by using some convenient yet powerful text manipulation languages and/or utilities such as sed, awk, regex, perl,...

python - manipulate text file line by line or as a whole string?

for line in open('file.txt'): print(re.sub('windows', 'linux', line)) or print(re.sub('windows', 'linux', open('file.txt').read())) Which one is better? Is there any differences? BTW. Is is a good idea to manipulate a huge string with a regex?

Python scapy: pcap file read, manipulate and write pcap

I want to read a pcap file using python scapy, manipulate the TCP payload (e.g. delete the current payload and replace it with 0s) and write the manipulated packets to a new pcap file.

python - Use Perl to manipulate file from within Octave

I have a need to manipulate a file from within Octave in the middle of a routine. At the moment I end this routine by saving a file from Octave with save data_for_training -ascii train_data and then manually, and tediously, edit the saved file and then resume operations in a new and different Octave routine by first reading the edited file. Conceptually the file manipulations required are ...

python - Manipulate string data

I'm new to python and trying to create a script to modify the output of a JS file to match what is required to send data to an API. The JS file is being read via urllib2. def getPage(): url = "http://url:port/min_day.js" req = urllib2.Request(url) response = urllib2.urlopen(req) return response.read() # JS Data # m[mi++]="19.12.12 09:30:00|1964;2121;3440;293;60" # m[mi++]="19.12.12 09:25:00...

manipulate python lists into string type i want

I have a nested list that is for example: A_board=[['0', '0'],['1', '1']]. And I want to take this nested list apart and get a result, which if I call print result, it would display: &lt; 0 0 &gt; &lt; 1 1 &gt; I am not sure how to approach this with loops, I made the matrix into a list first, by doing: boardWidth_a=len(A_board) listLength=len(board) for q in range(0,bo...

python - How can I manipulate lists?

In the computer algebra system Sage, I need to multiply a list by 2. I tried the code sage: list = [1, 2, 3]; sage: 2 * list which returns [1, 2, 3, 1, 2, 3] How can I just multiply each element by two?

Manipulate screen buffer in python

I know this is a long shot, but I was wondering if Python had a way to manipulate the screen buffer. Specifically, I want to be able to gray-out my desktop and highlight my windows when I press a key combination. Is this in the realm of possibility?

python - Manipulate table values with PyObjC and Core Data

I recently started programming with xCode and PyObjC and I'm trying to create a logistics application. I have a table with the store's items and a second table with the expenses. Until now everything worked ok by using just the interface builder to link values to core data information and I didn't have to write any code. Now the problem is that I have an attribute "cost" in the expenses table which should not be entered by...

c++ - Can I use XPCOM to create and manipulate a Firefox window as I would use win32 COM with IE?

With win32 COM I create an Internet Explorer instance and control it almost fully from my python code (manipulate windows, DOM elements, etc). More specifically, using DispatchEx('InternetExplorer.Application'). Can I do the same using XPCOM and C++/python? I need to automate certain actions taken on the html ui of some websites, so no I can't use urllib and I can't use selenium, because it doesn't work with cross-...

python - Manipulate and print to PDF files in a script

I have several pdf files of some lecture slides. I want to do the following: print every pdf file to another pdf file in which there are 6 slides per page and then merge all the resulting files to one big file while making sure that every original file starts on an odd page number (Edit: obviously, it will be printed in duplex) (possibly adding blank pages when necessary). Is that possible?

Python: How do i manipulate the list to get the string starting with '+'?

I am comparing 2 txt files that are ls -R of the etc directory in a linux system. I compared the 2 files using difflib.differ and got this list as my result (i put the dots to keep the list short in here): result = [' etc:\n', ' ArchiveSEL\n', ' HOSTNAME\n', ' RMCPUser\n', ..., ' qcleaner\n', '+ extraFile\n', ' rc.d\n', '+ extraFile2\n', ..., ' resolv.conf\n', ' wu-ftpd\n']...

python - Django: How to manipulate a Model object before adding it to DB?

In Python-Django, I've got a Model with a FileField member in it. This member stores video files. I'd like to "interfere" with the standard "add model row/object/instance" proecdure of Django, and manipulate each video I'm adding, before actually committing or adding it to database. The manipulation is to convert the video to a specific uniform format. Thus, all added videos will eventually be stor...

html - Manipulate website dropdown menu in Python

I've been searching the web for an answer to the following question, and my lack of success might have to do with my inexperience in web programming/html. If so and there's an obvious answer, sorry for bugging you all. I've been trying to parse a bunch of text from a website, and I found the python script html2text.py, which does a nice job of presenting the website in a way that I can parse. However, in order to get to ...

python - How to manipulate the following text

I was wondering how to convert text similar to the following: Chapter 3 Convex Functions 97 3.1 Definitions 98 3.2 Basic Properties 103 to: ("Chapter 3 Convex Functions 97" "#97") ("3.1 Definitions 98" "#98") ("3.2 Basic Properties 103" "#103") by using some convenient yet powerful text manipulation languages and/or utilities such as sed, awk, regex, perl,...

php - Manipulate PDF files (read, split, combine, move)

I'm trying to figure out a way to deal with scanned pdf's with either Python or PHP. I need to be able to open a multiple page PDF, read the contents, and move the pages to individual PDF files (or one file if they are to be grouped) based on an identifier in the text. I downloaded and have played around a little bit with pdftotext, but am unsure wh...