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?
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.
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.
(~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.
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.
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.
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With