473,387 Members | 1,541 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Bitwise OR?

Why is 3500 | -67 equal to 3500 instead of -3567?

Mar 24 '06 #1
10 1914
xkenneth schrieb:
Why is 3500 | -67 equal to 3500 instead of -3567?


It isn't - its -67.

Diez
Mar 24 '06 #2

xkenneth wrote:
Why is 3500 | -67 equal to 3500 instead of -3567?


Well that's funny... On my computer, python says it's -67. Java also
says it's -67.

Haven't yet looked at the actual bits of both values.
What Python implementation and what machine do you have?

--Tim

Mar 24 '06 #3
Actually, following up to my own reply:

3500 | 67 = 3567. So perhaps that sets your expectations for 3500 |
-67.

But try

-3500 | -67

for fun: it is -3

Bitwise or is no arithmetic and if you want to predict something about
the resulting integers, you should know something about how they are
stored.

Negative integers are stored in 2-complement format: minus 1 is all
bits set to 1. Turning bits off makes it a more negative number (as
long as you don't touch the sign-bit) and turning more bits on makes it
a smaller negative number.

Doing bitwise-OR for the positive numbers 3500 and 67 results in 3567:
proof that they don't have any overlapping bits.
Know it turns out that 3500 and -67 have only overlapping bits:
therefore the result is -67. (adding the bits from 3500 to the bits of
-67 doesn't turn on any extra bits).

Use bit operators to manipulate bits, and think of the operands as sets
of bits. Bitwise OR is the union of 2 sets of bits.
Don't think of the operands to bit operators as numbers, and don't try
to do your sums using bitwise or!

:-)

--Tim

Mar 24 '06 #4
To look at the bit-structure i've implemented a little function:

def bitstring(number, digits=32):
"""lsb------>msb"""
result = ""
for a in xrange(digits):
if number & 1:
result += '1'
else:
result += '0'
number >>= 1
return result

I wonder if there is something like sizeof() for int numbers.

mfg
- eth
Mar 24 '06 #5
Hello,

I've written a little (optimized) method to get a bit-string:

def bitstringneg(number, digits=32):
"""optimized for negative numbers"""
result = ""
for a in xrange(digits):
if number & 1:
result += '1'
else:
result += '0'
number >>= 1
return result

def bitstringpos(number):
"""optimized for positive numbers"""
result = ""
while number:
if number & 1:
result += '1'
else:
result += '0'
number >>= 1
return result

def bitstring(number, digits=32):
"""lsb------>msb"""
result = ""
if number < 0:
return bitstringneg(number, digits)
else:
return bitstringpos(number)

BTW: Is there something like a sizeof() method for int numbers?

mfg
- eth
Mar 24 '06 #6
I wonder what causes one version to be faster for positive, and the
other faster for negative numbers? I can see that the pos-version
doesn't make as many iterations as the neg version, but it doesn't pad
the length of the result to the requested number of digits and
potentially produces more digits.

I also wonder if it wouldn't be faster to put the numbers into a list
and join the list into a string -- did you test with that?

Cheers,

--Tim

Mar 24 '06 #7
Tim N. van der Leeuw wrote:
I also wonder if it wouldn't be faster to put the numbers into a list
and join the list into a string -- did you test with that?


It will be faster - the naive string concatenation is quadratic, whereas the
list-based approach is linear.

Diez
Mar 24 '06 #8
On Fri, 2006-03-24 at 12:55 +0100, Clemens Hepper wrote:
Hello,

I've written a little (optimized) method to get a bit-string:

def bitstringneg(number, digits=32):
"""optimized for negative numbers"""
result = ""
for a in xrange(digits):
if number & 1:
result += '1'
else:
result += '0'
number >>= 1
return result

def bitstringpos(number):
"""optimized for positive numbers"""
result = ""
while number:
if number & 1:
result += '1'
else:
result += '0'
number >>= 1
return result

def bitstring(number, digits=32):
"""lsb------>msb"""
result = ""
if number < 0:
return bitstringneg(number, digits)
else:
return bitstringpos(number)

BTW: Is there something like a sizeof() method for int numbers?


import struct
help( strict.calcsize )

Why one bit at a time?
If I rewrite your functions as:

_octets = {"0":"000", "1":"001","2":"010",
"3":"011", "4":"100","5":"101",
"6":"110", "7":"111", "-":"" }

_sign = {True:'-',False:''}

def bitstring1( number ):
return _sign[number<0] + ''.join( [_nibbles[d] for d in
hex( number )] ).lstrip( '0' )
_nibbles = {"0":"0000", "1":"0001", "2":"0010", "3":"0011",
"4":"0100", "5":"0101", "6":"0110", "7":"0111",
"8":"1000", "9":"1001", "a":"1010", "b":"1011",
"c":"1100", "d":"1101", "e":"1110", "f":"1111",
"-":"", "x":""}
def bitstring2( number ):
return _sign[number<0] + ''.join( [_nibbles[d] for d in
hex( number )] ).lstrip( '0' )

Now I know, my negative number sematincs are different than yours, I'll
leave fixing that as an exercise to you.
python2.4 -mtimeit -s 'from test_a import bitstring'
'bitstring(343890242);bitstring(-343890242)'
10000 loops, best of 3: 27.1 usec per loop

python2.4 -mtimeit -s 'from test_b import bitstring1'
'bitstring1(343890242);bitstring1(-343890242)'
100000 loops, best of 3: 10.9 usec per loop

python2.4 -mtimeit -s 'from test_b import bitstring2'
'bitstring2(343890242);bitstring2(-343890242)'
100000 loops, best of 3: 11.2 usec per loop
And if I use a map, well, its not a statistically significant
difference.

def bitstring_nibblemap( number ):
return _sign[number<0] + ''.join( map( _nibbles.get,
hex( number ))).lstrip( '0' )

python2.4 -mtimeit -s 'from test_b import bitstring_nibblemap'
'bitstring_nibblemap(343890242);bitstring_nibblema p(-343890242)'
100000 loops, best of 3: 10.7 usec per loop
Cheers - Adam

Mar 24 '06 #9
Adam DePrince wrote:
BTW: Is there something like a sizeof() method for int numbers?
import struct
help( strict.calcsize )

Mh, that doesn't do what i want. I'd like to have something like:

def size(number):
return sizeof(number)
Why one bit at a time?
Good question...

Here my new approach based on your idea:

_digits = { 0:"0000", 1:"1000", 2:"0100", 3:"1100",
4:"0010", 5:"1010", 6:"0110", 7:"1110",
8:"0001", 9:"1001", 0xa:"0101", 0xb:"1101",
0xc:"0011", 0xd:"1011", 0xe:"0111", 0xf:"1111"}

def bitstring2(number):
"""lsb------>msb"""
rlist = list()
if number >= 0:
while number:
rlist.append( _digits[number & 0xF] )
number >>= 4
else:
while number != -1:
rlist.append( _digits[number & 0xF] )
number >>= 4

return ''.join(rlist)

This was faster for positive numbers. For negative numbers yours was
faster, but my version handles those numbers different.

Your version fails for Large numbers since hex( long ) returns
something like "0xFFFL" instead of "0xfff".
Cheers - Adam


Cheers :)
- eth
Mar 26 '06 #10
Okay... pythons build-in methods are quite fast. so is hex().

with about 64 kb memory i can write it with a 16 bit dictionary
where the dictionary generation itself is not yet optimized:

def genBitList(exp):
next = lambda now: [x+'0' for x in now]+[x+'1' for x in now]
result = [""]

for x in range(exp):
result = next(result)

return result

_digits = genBitList(16)

def bitstring2(number):
"""lsb------>msb"""
rlist = list()
if number >= 0:
while number:
rlist.append( _digits[number & 0xFFFF] )
number >>= 16
return ''.join(rlist).rstrip('0')
else:
while number != -1:
rlist.append( _digits[number & 0xFFFF] )
number >>= 16
return ''.join(rlist).rstrip('1')

this is quite fast and in lots of cases faster than the
hex()-version. however your method (with my inverses formatting) is
very fast, too and without so much memory expense:

_nibbles = {"0":"0000", "1":"0001", "2":"0010", "3":"0011",
"4":"0100", "5":"0101", "6":"0110", "7":"0111",
"8":"1000", "9":"1001", "a":"1010", "b":"1011",
"c":"1100", "d":"1101", "e":"1110", "f":"1111",
"l":"", "-":"", "x":""}

from string import maketrans, translate

_invert = maketrans('01', '10')

def bitstring3( number ):
if number > 0:
return ''.join( [_nibbles[d] for d in
hex( number ).lower()] ).lstrip( '0' )
else:
return translate(''.join( [_nibbles[d] for d in
hex( ~number ).lower()] ).lstrip( '0' ), _invert)

Benchmark:
for 0xa:
bitstring2: 0.61802315712
bitstring3: 0.91001200676

for 0xaaaa:
bitstring2: 0.561501026154
bitstring3: 1.11787199974

for 0xaaaaaaaaaaaa:
bitstring2: 1.2295820713
bitstring3: 1.61559510231

for 0xaaaaaaaaaaaaaaaaaaaaaaaa:
bitstring2: 1.90036797523
bitstring3: 2.2683339119

for -0xaaaaaaaaaaaaaaaaaaaaaaaa:
bitstring2: 2.81339716911
bitstring3: 2.74266886711

mfg
- eth
Mar 27 '06 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: jas_lx | last post by:
The basic understanding of what bitwise operators (& ^ | >> << ) comes fairly simple, as long as one has a fundamental understanding of bits, bytes and binary. Having done some Win32...
2
by: Steve Summit | last post by:
-----BEGIN PGP SIGNED MESSAGE----- It's often explained that the reason for some of the imprecision in C's definition is so that C can be implemented on different kinds of machines -- say, those...
8
by: Paul E Collins | last post by:
Suppose I have a few Keys objects: Keys k1 = Keys.V; // V Keys k2 = Keys.Control | Keys.V; // Ctrl+V Keys k3 = Keys.Shift | Keys.J; // Shift+J I need to determine which of these include the...
9
by: Christopher Weaver | last post by:
I know that the bitwise AND of 8 and 4 will return 0 or false and the bitwise AND of 8 and 9 will return 1 or true but I don't know how to write the synax for it in C#. I have a value that ranges...
5
by: noridotjabi | last post by:
I'm learning to program in C and any tutorial or book that I read likes to briefly touch on birdies operators and then move on without giving any sort of example application of them. Call me what...
2
by: Mark Rae | last post by:
Hi, This isn't *specifically* an ASP.NET question, so I've also posted it in the ADO.NET group - however, it's not too far off-topic... Imagine a SQL Server 2005 database with a table with an...
3
by: Jay Ruyle | last post by:
I'm trying to figure out a way to list several items in a listbox and let the user select any number of items in the listbox. I have tried to code in the items as bitwise items but all it stores...
5
by: Gigs_ | last post by:
Can someone explain me bitwise expression? few examples for every expression will be nice x << y Left shift x >y Right shift x & y Bitwise AND x | y Bitwise OR x ^ y Bitwise XOR (exclusive...
45
by: Carramba | last post by:
Hi! I now that I can't do straight forward any bitwise operation on float (double etc..). But I wondering what is the easiest/best way to do this? I was thinking if I have float x=1.1111 so I can...
29
by: Carl Banks | last post by:
Anyone with me here? (I know the deadline for P3 PEPs has passed; this is just talk.) Not many people are bit-fiddling these days. One of the main uses of bit fields is flags, but that's not...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.