0

I'm new to bit operations and trying to experiment little bit.

let's say I have a 32 bit register which is constructed as follows:

Bit 31:12 RESERVED
Bit 11    CONFIG1
Bit 10    CONFIG2
Bit 9:0   DATA

There exists already a Function to write data into the register:

 #define WR_REG_32(address, value)    (*((volatile u32 *)(address)) = (value))

I would like to write the value 0x0 at Bit 10 (CONFIG2). The value should be in the format like for example:

0x00005000 

So, how to know what hex value to use in order to write to Bit 10 the value 0x0 without touching the other bits?

Also, what is the easiest way to read from the 32 bit register only the values from bit 0 - 9 ?

JohnDoe
  • 825
  • 1
  • 13
  • 31
  • 1
    Bitwise operations as shift, and, or etc. are made for this purpose. If register has 32 bits, 32 bits you will read. Only then you can use aforementioned operations to get bits you want. – zubergu Dec 01 '17 at 14:21
  • from the top of the Related list: [How do you set, clear, and toggle a single bit?](https://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit?rq=1)... – ilkkachu Dec 01 '17 at 14:38
  • 1
    Also: https://stackoverflow.com/questions/10493411/what-is-bit-masking – ilkkachu Dec 01 '17 at 14:40

1 Answers1

1

You need to read first the register to write the same bits, except the bit 10 forced to zero.

To force a bit to zero, bit 10, you have to use the bitwise AND between the current value and all-bits-to-1-except-bit-10 (zero)

 newValue = currentValue & ~(1<<10)

The ~ operator invert bits. & is bitwise AND. Using the macro,

value = RD_REG_32(address)    ; To read the current value
WR_REG_32(address, value & ~(1<<10))

RD_REG_32 to read the current value.

To read the bits 0~9, set the others to 0

(read value from register)
value &= 0x3FF;     // keeps only the first 10 bits, from 0 to 9

Read also Eric's comment below. Your architecture might impact the way you can deal with 32 bits values.

Déjà vu
  • 28,223
  • 6
  • 72
  • 100
  • 2
    `int` may be 16 bits, in which case `~(1<<10)` evaluates to `~1024` and then `64512` (assuming two’s complement), and then `value & ~(1<<10)` clears the high 16 bits of `value`. Generally, when using bitwise operations, it is good to use an unsigned type of the desired width, as with `value & ~((u32) 1 << 10)`. – Eric Postpischil Dec 01 '17 at 14:37