Avatar

Original Post

空明 2015-01-23 20:33 CST

We want to have a portable C implementation of this function. Would you like to give some examples?

Thanks!

1

Avatar

The fast and portable implementation: looking into a prepared table.

空明 2015-01-23 20:35 CST

static int nr_bits_all_bytes [sizeof (unsigned char)];
 
static int get_nr_one_bits_slow (unsigned char ch)
{
    int i;
    int count = 0;
 
    for (i = 0; i < 8; i++) {
        if ((ch >> i) & 0x01) {
            count ++;
        }
    }
 
    return count;
}
 
// Call this function once before call get_nr_one_bits
void init_nr_bits_all_bytes (void)
{
    unsigned char ch;
 
    for (ch = 0; ch < sizeof (unsigned char); ch++) {
        nr_bits_all_bytes [ch] = get_nr_one_bits_slow (ch);
    }
}
 
int get_nr_one_bits (unsigned char ch)
{
    return nr_bits_all_bytes [ch];
}
Your anwser
20 characters at least.

Sign in to post your answer.

Your note
Markdown Extra enabled. 20 characters at least.

Sign in to post your note.

Your reference
#1
@
#2
@
#3
@
#4
@

Sign in to post your reference.

  • Top Q&A
  • Normal Q&A
  • 1 How to fast calculate the number of true bits in a byte?