Hacker News new | past | comments | ask | show | jobs | submit login

Yes, even for web applications, bitwise manipulation will come in handy at some point.

Personal anecdote: I recently had to combine two arbitrary unsigned 32 bit integers into one unsigned 64 bit integer to make a unique ID for an index. Not sure how I would have done that without bitwise manipulation.




lol.

in python: (2 ^ 32)*upper + lower

edit: dbl star goes blank .. so in almost python


You're XORing 32 into 2, multiplying it by the top word, and adding the bottom word?

Also, you think exponentiation and multiplication is faster than a shift and an OR? I think you're the target audience for this article, and I revise my opinion (thankfully unstated) about whether this is material every developer "must" know.


Surprisingly (I just benchmarked it myself), the times are near the same.

Here's my benchmark (in case I made a mistake):

  import time

  def combine(upper,lower): return (2**32)*upper + lower
  def combine2(upper,lower): return (upper << 32) | lower

  def test_combine():
  	start = time.clock()
	for i in range(10000000):
		combine(i,i)
	end = time.clock()
	output = 'The time taken for combine() is ' + str(end - start)
	print output

  def test_combine2():
	start = time.clock()
	for i in range(10000000):
		combine2(i,i)
	end = time.clock()
	output = 'The time taken for combine() is ' + str(end - start)
	print output
Also see http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Pyth...


That's surprising; it's more than twice as slow in Ruby (yeah, yeah). It's also (for obvious reasons) orders of magnitude faster in C --- if you were crazy enough to actually write code that way.


I don't know much about Python so forgive me if this is stupid - but could 2^32 have been optimized as a constant, so that the result is just a multiplication and an addition?


Okay okay ... I should have written:

import math; math.pow(2,32)

I tried to use the double star operator, but that is markup for italics in this software, so it was edited out.


I considered that solution. And in thinking about why I chose to do bit-shifting, I remembered why: I actually needed to combine two _signed_ 32 bit integers in MySQL, and since I wasn't sure how signed integers are stored in MySQL, I figured that I could just use bit-shifting and move on.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: