2
0010 1101 1011 0100 0111 1100 1000 0101

i would like to right shift 26,but failed

print(bin(00101101101101000111110010000101) >> 26)

and the debug error is SyntaxError: invalid token

right shift 26 should be return 1011

how about this?

0010 1101 1011 0100 0111 1100 1000 0101

Shift 0010 1101 1011 0100 0111 1100 1000 0101>>22 returns 10110110 And with 00001111 returns 0110 converts to decimal 6 ?

with 00001111?how to do this with 00001111?

mgilson
  • 300,191
  • 65
  • 633
  • 696

4 Answers4

3

Your use of bin() is wrong. The documentation states:

Convert an integer number to a binary string.

Since that is not what you're after, that is wrong. You're trying to right-shift a string, which isn't possible.

You mean:

print(0b00101101101101000111110010000101 >> 26)

or, if you want the answer as a binary string:

print(bin(0b00101101101101000111110010000101 >> 26))

Here, the prefix 0b is used in Python for a binary number literal.

unwind
  • 391,730
  • 64
  • 469
  • 606
2

bin returns a string which is the string's binary representation.

print (0b00101101101101000111110010000101 >> 26)

should work I think.

The syntax error that you're seeing is because an integer literal can't start with 0 in python3.x -- In python2.x, that meant that you wanted to declare an octal literal.

e.g. (python2.x):

>>> print 025
21
mgilson
  • 300,191
  • 65
  • 633
  • 696
1
  • Prefix your binary number with 0b to indicate to Python it is a binary number.
  • First shift right, then convert it to binary.

Try this:

print(bin(0b00101101101101000111110010000101 >> 26))

Edit: outputs:

0b1011
Sjoerd
  • 74,049
  • 16
  • 131
  • 175
0

Reading the documentation for Python bin(), it looks like you should be passing bin() a decimal integer, so it's interpreting 00101101101101000111110010000101 as decimal.

Kyle Maxwell
  • 617
  • 6
  • 20
  • Well, as you noted above, that's a Python 2 vs 3 issue, right? :) – Kyle Maxwell Jan 28 '13 at 15:36
  • Sort of -- But 001... isn't interpreted as a *decimal* in any version of python. In python2.x it's interpreted as *octal*, in python3.x, it's a syntax error. -- Maybe you meant to say that it's **NOT** interpreting 001011011... as decimal? – mgilson Jan 28 '13 at 15:38