Efficiently generating bits

N

nish.sinnadurai

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
 
B

Ben Pfaff

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.
 
N

nish.sinnadurai

Ben said:
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
 
S

spibou

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 ?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top