Efficiently generating bits

Discussion in 'C Programming' started by nish.sinnadurai@gmail.com, Jul 16, 2006.

1. Guest

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

, Jul 16, 2006

2. Ben PfaffGuest

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

Ben Pfaff, Jul 16, 2006

3. Guest

Ben Pfaff wrote:
> 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

, Jul 16, 2006
4. Guest

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 ?

, Jul 16, 2006