Martin
Martin

Reputation: 223

Getting the integervalue of bits inside an unsigned int

I want to write a kernel module which reads out a register, (return value is saved in an unsigned int) and then read the the bits 16 to 22 from this variable and the convert it to an integer number. The conversion is no problem. But getting the bits out in the first place is the problem. As example I have this 2 values in hex:

0x88290000d
0x005a0a00d

and from this 2 values I want the bits 16 to 22 as integer, any ideas how I can implement that in my kernel module ?

Upvotes: 1

Views: 148

Answers (2)

Vishwajeet Vishu
Vishwajeet Vishu

Reputation: 492

You can define a mask that is active for only 7 bits(16 bit to 22 bit). So your mask will be defined as.

mask=0x007F0000   //Your mask
var2=0x00270f00   //Variable which you want to mask
result=mask & var2 // bitwise-and operation to mask the value
result>>=16       // right shift the value to get only this value.

Hope this helps :)

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Here is how you extract bits 16 through 22, inclusive (7 bits):

  1. Read the number from the register into unsigned int reg = ...
  2. Shift reg to the right by 16, so bit 16 is at the least significant position: reg >>= 16
  3. Mask the number with 00000000011111112, which is 0x7F: reg &= 0x7F

Note: The above counts bits starting from zero (the traditional way of numbering bits).

Upvotes: 2

Related Questions