Velocity Reviews > Efficiently generating bits

# Efficiently generating bits

nish.sinnadurai@gmail.com
Guest
Posts: n/a

 07-15-2006
Hi,

I have two code snippets here and I'm wondering which is better, and
whether or not there is a better way to do the following:

I want to fill in an unsigned int variable with n 1s. Example: n = 4
--> var = 00...001111 in binary.

So,

Method 1:

var = 0;
var = pow(2, n) - 0.9999;

Method 2:

var = 0;
for(i = 0; i < n; i++)
var = var << 1 + 1;

---

I'm not quite sure which method is better (wrt to computational time),
or if there is a more elegant way to do this.

Can anyone help me out here?

Thanks!
Nish

UW09

Ben Pfaff
Guest
Posts: n/a

 07-15-2006
http://www.velocityreviews.com/forums/(E-Mail Removed) writes:

> I want to fill in an unsigned int variable with n 1s. Example: n = 4
> --> var = 00...001111 in binary.

If n is less than the number of value bits in an unsigned int:
x = (1u << n) - 1;
If n might be (greater than or) equal to the number of value
bits:
x = n < NUM_VALUE_BITS ? (1u << n) - 1 : UINT_MAX;
where NUM_VALUE_BITS is the width of unsigned int, which is
typically CHAR_BIT * sizeof (unsigned int) but might be smaller.
--
"If I've told you once, I've told you LLONG_MAX times not to
exaggerate."
--Jack Klein

nish.sinnadurai@gmail.com
Guest
Posts: n/a

 07-16-2006

Ben Pfaff wrote:
> (E-Mail Removed) writes:
>
> > I want to fill in an unsigned int variable with n 1s. Example: n = 4
> > --> var = 00...001111 in binary.

>
> If n is less than the number of value bits in an unsigned int:
> x = (1u << n) - 1;

This method is really good.

Soon after I posted I thought of:

var = ~((~0u) << n);

but yours seems to be the best solution.

Thanks!
Nish

spibou@gmail.com
Guest
Posts: n/a

 07-16-2006

(E-Mail Removed) wrote:

> Hi,
>
> I have two code snippets here and I'm wondering which is better, and
> whether or not there is a better way to do the following:
>
> I want to fill in an unsigned int variable with n 1s. Example: n = 4
> --> var = 00...001111 in binary.
>
> So,
>
> Method 1:
>
> var = 0;
> var = pow(2, n) - 0.9999;
>
> Method 2:
>
> var = 0;
> for(i = 0; i < n; i++)
> var = var << 1 + 1;

Is var a double or int ?

 Thread Tools

 Posting Rules You may not post new threads You may not post replies You may not post attachments You may not edit your posts BB code is On Smilies are On [IMG] code is On HTML code is OffTrackbacks are On Pingbacks are On Refbacks are Off Forum Rules

 Similar Threads Thread Thread Starter Forum Replies Last Post jidanni@jidanni.org Perl Misc 1 09-21-2009 04:27 PM Rajarshi Guha Python 2 03-06-2004 07:42 PM Terry Digital Photography 5 01-21-2004 06:59 PM Al Dykes Digital Photography 3 12-29-2003 07:08 PM Abbyss Computer Support 3 11-13-2003 12:39 AM

Advertisments