Search code examples
bit-manipulationbitbit-shiftcpu-registersbit-fields

Getting value from a 16-bit register


I have a 16-bit register

  • At bit 0 the value is 0
  • At bit 1...2 the value is 3
  • At bit 3 the values is 1
  • At bit 4 the value is 1

So in the end the written value in my register is 30 because:

(0 x 1) + (3 x 2) + (1 x 8) + (1 x 16) = 30  

Now I want to do reverse to get which value is written in the bits:

(30 & 1) / 1 = 0  
(30 & 2) / 2 = 1 (this is wrong, it should be 3)  
(30 & 8) / 8 = 1  
(30 & 16) / 16 = 1  

What I'm doing wrong?


Solution

  • (30 & 2) / 2 = 1 (this is wrong, it should be 3)
    

    This is wrong. To get 2 bits you must and with 3 shifted by its bit position. In this case you and with 3 << 1 = 6

    (30 & 6) / 2 = 3