Extract bits using bit manipulation

I have a 32-bit unsigned int, and I need to extract the bits at the given positions and make a new number from these bits. For example, if I have 0xFFFFFFFF and want the 0.10.11 bit, my result will be 7 (111b).

This is my attempt, it extracts the bits correctly, but does not produce the correct result. I shift the result 1 place to the left and USING it with my bit extracted, but this is not true though?

I'm also sure there is probably a much more elegant way to do this?

#define TEST 0xFFFFFFFF unsigned int extractBits(unsigned short positions[], unsigned short count, unsigned int bytes) { unsigned int result = 0; unsigned int bitmask = 0; unsigned short bit = 0; int i = 0; for(i = 0; i < count; i++) { bitmask = 2 << (positions[i] -1); if(bitmask == 0) bitmask = 1; bit = bytes & bitmask; bit = bit >> positions[i]; result = result << 1; result = result & bit; } if(result != 31) { printf("FAIL"); } return result; } int main(void) { unsigned short positions[5] = {8, 6, 4, 2, 0}; unsigned int result = extractBits(positions, 5, TEST); printf("Result: %d\n", result); return 0; } 
+2
source share
2 answers

Since you select individual bits, there is no reason for the bitmask to be variable; just shift the desired bit into units bit and use mask 1. For example:

 ... result = (2*result) | ((bytes >> positions[i]) & 1); ... 

Many compilers generate the same code for 2*result and result<<1 , so use what you like.

Please note that if you are developing an interface and have no good reason to use short integers short for positions[] and count , like you do, then no. Be consistent and specify all integers equally.

+1
source

Beware, untested code:

 for(i = 0; i < count; i++) { bitmask = 1 << positions[i]; bit = (bytes & bitmask)!=0; result = (result << 1)|bit; } 
+2
source

Source: https://habr.com/ru/post/1272739/


All Articles