1

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 ?

Martin
  • 221
  • 3
  • 14

2 Answers2

2

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).

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • OP's `0x88290000d` may easily not fit as in `unsigned int reg = 0x88290000d;` – chux - Reinstate Monica Jun 20 '17 at 13:37
  • This Answer worked perfect. But now i have a other problem, i did the same twice with 2 different values, i printed everything out and worked. Then I removed the debug printk's and the value was 0, after putting them in again i had the correct value, you have any ideas on that too ? – Martin Jun 20 '17 at 13:43
  • @MartinWalzl When printing a value changes the way the program works, it means there is undefined behavior in your code. Post a separate question with details on what you did and how you printed the values, or run your code through [valgrind](http://valgrind.org/) if it is available on your platform. – Sergey Kalinichenko Jun 20 '17 at 13:47
0

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 :)

Vishwajeet Vishu
  • 492
  • 3
  • 16