3
votes

I am sorry if my question is confusing but here is the example of what I want to do,

lets say I have an unsigned long int = 1265985549 in binary I can write this as 01001011011101010110100000001101

now I want to split this binary 32 bit number into 4 bits like this and work separately on those 4 bits

0100 1011 0111 0101 0110 1000 0000 1101

any help would be appreciated.

3
the C++ solution would be to use a std::bitset, and then shift and mask out the nibbles.tillaert
Could you be more specific about what you want to do with the nibbles? Usually with bit manipulation it's not necessary to split things into fields, they're already implicitly subdivided all the way down to separate bits - just don't do anything that can transfer information from one field to an other.harold
I'm checking the number of 1's in one nibble and then if its odd i add 1 to my variable or if its even then I add 0, and form another 8 bit number.Astronautilus
@Astronautilus good, that's an example of a case in which you don't actually have to extract the nibblesharold

3 Answers

6
votes

You can get a 4-bit nibble at position k using bit operations, like this:

uint32_t nibble(uint32_t val, int k) {
    return (val >> (4*k)) & 0x0F;
}

Now you can get the individual nibbles in a loop, like this:

uint32_t val = 1265985549;
for (int k = 0; k != 8 ; k++) {
    uint32_t n = nibble(val, k);
    cout << n << endl;
}

Demo on ideone.

4
votes
short nibble0 = (i >>  0) & 15;
short nibble1 = (i >>  4) & 15;
short nibble2 = (i >>  8) & 15;
short nibble3 = (i >> 12) & 15;

etc

1
votes

Based on the comment explaining the actual use for this, here's an other way to count how many nibbles have an odd parity: (not tested)

; compute parities of nibbles
x ^= x >> 2;
x ^= x >> 1;
x &= 0x11111111;
; add the parities
x = (x + (x >> 4)) & 0x0F0F0F0F;
int count = x * 0x01010101 >> 24;

The first part is just a regular "xor all the bits" type of parity calculation (where "all bits" refers to all the bits in a nibble, not in the entire integer), the second part is based on this bitcount algorithm, skipping some steps that are unnecessary because certain bits are always zero and so don't have to be added.