Digital said:

I'd like to be able to create an integer from a range of contiguous

bits

in another integer. I'm on a big-ending machine, in case that matters.

I would ideally like to create a function with this prototype:

unsigned long long extractValue(unsigned long long target, int a, int

b)

where a and b are the range of bits counted off from the most

significant

bit (where the msb is the 0th bit). For instance, 12345678900 is

00000000 00000000 00000000 00000010 11011111 11011100 00011100

00110100

A call to extractValue(value, 32, 35) should result in 13 (1101 in

binary).

Can someone please help?

You've chosen an unhelpful way of specifying the bits you want.

The idea is that we shift enough bits to the left for the desired MSB to

be the actual MSB, then shift back to make the desired LSB the actual

LSB, losing undesired bits in the overflow. This can be done in one

expression, but I'll do it in more for clarity.

#include <limits.h>

unsigned long long extractValue(unsigned long long target, int msb,

int lsb) {

const size_t ull_bits = CHAR_BIT * sizeof(unsigned long long);

unsigned long long result;

if (msb > lsb) {

/* empty range */

result = 0;

} else {

/* shift the desired msb to the actual msb */

result = target << msb;

/* there are (lsb - msb + 1) bits in the range, shift them

from high to low */

result >>= ull_bits - (lsb - msb + 1);

}

return result;

}

This function does not check if the arguments are in range; it assumes

you know what bits you can access.

S.