Re: bit vector question: why shift (>>) 5?
- From: gokkog@xxxxxxxxx
- Date: 16 Sep 2006 19:18:21 -0700
Jean-Marc Bourguet wrote:
"Bill Pursell" <bill.pursell@xxxxxxxxx> writes:
gokkog@xxxxxxxxx wrote:
Recently I have the book Programming Pearls. Nice read! Perhaps it is
weekend, I cannot understand the following codes well:
#define BITSPERWORD 32
#define SHIFT 5
#define MASK 0x1F
#define N 10000000
int a[1 + N/BITSPERWORD];
void set(int i) { a[i>>SHIFT] |= (1<<(i & MASK)); }
void clr(int i) { a[i>>SHIFT] &= ~(1<<(i & MASK)); }
int test(int i){ return a[i>>SHIFT] & (1<<(i & MASK)); }
From http://netlib.bell-labs.com/cm/cs/pearls/bitsort.c
Why Jon #define SHIFT 5? (and #define MASK 0x1F)? Are there any
differences if I define SHIFT as 3? How about 8?
Are you sure this is "Programming Pearls" and not "Introduction
to Obfuscation?"
Note that the book was first published in the mid 80's and a collection of
columns published before. I don't know how much it has been revised in the
recent printings/editions.
I am reading the second edition (1999), according to the author, all
the example codes have been re-written.
This would be much more clearly written as: void set(int i) { a [ i /
BITSPERWORD ] |= (1 << ( i % BITSPERWORD));} etc. That should answer
your questions.
There are arguments that using the << operater will lead
to better code, but it's highly questionable. (Most compilers
will generate exactly the same code for the two.)
I don't think so (note: i is an *signed* int).
You are talking about specifically "<< as in (1<<...)" not ">> as in
a[i>>SHIFT]"? I tried both versions (Bill Pursell & Jon Bentley),
neither of them handles minus numbers correctly. So what is behind your
hint?
My thanks to all of you.
Wenjie
.
- Follow-Ups:
- Re: bit vector question: why shift (>>) 5?
- From: Jean-Marc Bourguet
- Re: bit vector question: why shift (>>) 5?
- From: CBFalconer
- Re: bit vector question: why shift (>>) 5?
- References:
- bit vector question: why shift (>>) 5?
- From: gokkog
- Re: bit vector question: why shift (>>) 5?
- From: Bill Pursell
- Re: bit vector question: why shift (>>) 5?
- From: Jean-Marc Bourguet
- bit vector question: why shift (>>) 5?
- Prev by Date: Re: Simple code leads to segfault.. help
- Next by Date: Computer Vitals
- Previous by thread: Re: bit vector question: why shift (>>) 5?
- Next by thread: Re: bit vector question: why shift (>>) 5?
- Index(es):
Relevant Pages
|