Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting bits from uint8_t type array

I have the data: ef324ad13255e219e8110044997cefaa43ff0954800000000000007 stored in an uint8_t type array called lfsr[36].

I want to extract specific bits from the array, e.g. bit no. 96, bit no. 184 etc.

How can I perform this operation?

like image 395
heisenburg007 Avatar asked Jun 12 '26 08:06

heisenburg007


1 Answers

As noted by barak manos, the proper code is

(lfsr[bit / 8] >> (bit % 8)) & 1

To explain it:


bit / 8 chooses an element from your array. Each element contains 8 bits, so dividing by 8 is an easy way to convert a bit index to an element index.


bit % 8 chooses a bit inside the element. This is most straightforward choice of indexing; it counts bits from the least significant bit to most significant bit (little-endian). Another variant is

7 - bit % 8

This variant counts the bits in reverse order (big-endian). Sometimes you have to use it (e.g. in JPEG) for compatibility reasons; if you are free to decide which bit order to choose, use little-endian (because it's easier).


The syntax (... >> ...) & 1 extracts one bit from a number. See here for details.

like image 72
anatolyg Avatar answered Jun 15 '26 02:06

anatolyg