Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split an unsigned long int (32 bit) into 8 nibbles?

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.

like image 761
Astronautilus Avatar asked Dec 18 '25 04:12

Astronautilus


2 Answers

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.

like image 200
Sergey Kalinichenko Avatar answered Dec 20 '25 20:12

Sergey Kalinichenko


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

etc

like image 21
sp2danny Avatar answered Dec 20 '25 22:12

sp2danny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!