Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to do bitwise operations on a string in Python?

This fails, not surprisingly:

>>> 'abc' << 8
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for <<: 'str' and 'int'
>>> 

With ascii abc being equal to 011000010110001001100011 or 6382179, is there a way to shift it some arbitrary amount so 'abc' << 8 would be 01100001011000100110001100000000?

What about other bitwise operations? 'abc' & 63 = 100011 etc?

like image 213
tMC Avatar asked Jun 08 '11 13:06

tMC


People also ask

Can you do bitwise operations on strings?

In computer programming, a bitwise operation operates on a bit string, a bit array or a binary numeral (considered as a bit string) at the level of its individual bits. It is a fast and simple action, basic to the higher-level arithmetic operations and directly supported by the processor.

Can you do bitwise operations in Python?

In Python, bitwise operators are used to performing bitwise calculations on integers. The integers are first converted into binary and then operations are performed on bit by bit, hence the name bitwise operators.

How do you write bitwise operators in Python?

(~a ) = -61 (means 1100 0011 in 2's complement form due to a signed binary number. The left operands value is moved left by the number of bits specified by the right operand. The left operands value is moved right by the number of bits specified by the right operand.

Can bitwise operators be used on which data type?

Bitwise operators work on binary digits or bits of input values. We can apply these to the integer types – long, int, short, char, and byte.


2 Answers

What you probably want is the bitstring module (see http://code.google.com/p/python-bitstring/). It seems to support bitwise operations as well as a bunch of other manipulations of bit arrays. But you should be careful to feed bytes into it (e.g. b'abc' or bytes('abc')), not characters - characters can contain Unicode and occupy more than one byte.

like image 174
Wladimir Palant Avatar answered Oct 02 '22 09:10

Wladimir Palant


It doesn't make any sense to do bitwise operations on strings. You probably want to use the struct module to convert your strings to numbers:

>>> import struct
>>> x = 'abc'
>>> x = '\x00' * (4-len(x)) + x
>>> number = struct.unpack('!i', x)[0]
>>> number
6382179

You can then do all your operations on number. When (if) you want a string back, you can do struct.pack('!i', number).

like image 25
Alok Singhal Avatar answered Oct 02 '22 10:10

Alok Singhal