Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #51524

Re: Bitwise Operations

References <mailman.5275.1375134621.3114.python-list@python.org> <kt6o8t$l55$1@reader1.panix.com> <51F6FBE8.8000106@Gmail.com>
Date 2013-07-30 00:44 +0100
Subject Re: Bitwise Operations
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.5289.1375141462.3114.python-list@python.org> (permalink)

Show all headers | View raw


On Tue, Jul 30, 2013 at 12:34 AM, Devyn Collier Johnson
<devyncjohnson@gmail.com> wrote:
>
> I understand the symbols. I want to know how to perform the task in a script
> or terminal. I have searched Google, but I never saw a command. Typing "101
> & 010" or "x = (int(101, 2) & int(010, 2))" only gives errors.

Your problem here isn't in the bitwise operators, but in your binary
literals. Python deliberately and consciously rejects 010 as a
literal, because it might be interpreted either as decimal 10, or as
octal (decimal 8), the latter being C's interpretation. Fixing that
shows up a more helpful error:

>>> x = (int(101, 2) & int(10, 2))
Traceback (most recent call last):
  File "<pyshell#74>", line 1, in <module>
    x = (int(101, 2) & int(10, 2))
TypeError: int() can't convert non-string with explicit base

The int() call isn't doing what you think it is, because 101 is
already an int. The obvious solution now is to quote the values:

>>> x = (int("101", 2) & int("010", 2))
>>> x
0

But there's an easier way:

>>> x = 0b101 & 0b010
>>> x
0

I think that might do what you want. Also check out the bin()
function, which will turn an integer into a string of digits.

ChrisA

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Bitwise Operations Devyn Collier Johnson <devyncjohnson@gmail.com> - 2013-07-29 17:25 -0400
  Re: Bitwise Operations Grant Edwards <invalid@invalid.invalid> - 2013-07-29 21:53 +0000
    Re: Bitwise Operations Devyn Collier Johnson <devyncjohnson@gmail.com> - 2013-07-29 19:34 -0400
      Re: Bitwise Operations Ulrich Eckhardt <ulrich.eckhardt@dominolaser.com> - 2013-07-30 08:20 +0200
    Re: Bitwise Operations Ethan Furman <ethan@stoneleaf.us> - 2013-07-29 16:41 -0700
    Re: Bitwise Operations Chris Angelico <rosuav@gmail.com> - 2013-07-30 00:44 +0100
    Re: Bitwise Operations Devyn Collier Johnson <devyncjohnson@gmail.com> - 2013-07-29 19:48 -0400
    Re: Bitwise Operations Chris Angelico <rosuav@gmail.com> - 2013-07-30 01:07 +0100
    Re: Bitwise Operations MRAB <python@mrabarnett.plus.com> - 2013-07-30 02:55 +0100
    Re: Bitwise Operations Terry Reedy <tjreedy@udel.edu> - 2013-07-30 01:46 -0400

csiph-web