# Thread: clearing bits using C macros

1. ## clearing bits using C macros

I am trying to clear bits using a C macro that gets m (clear bit start) and n (# bits to clear)
This macro needs to receive a reference to a 32-bit register and m and n.

For example:
I have a 32 bits value of: 0xFFFFFFFF
m = 5, n=2
so I would like my result to be: 0xFFFFFFAF

but I would like this function-macro to work with any m/n combimation

#define CLEAR_MN_BITS(reg_x, m, n) (??????????????)

Can anyone fill in the question marks?

Thanks!

2. Do you know any math or bitwise operators?

It could be something as simple as ((reg_x) - ((n) * (m) * 16))

3. Originally Posted by whiteflags
Do you know any math or bitwise operators?

It could be something as simple as ((reg_x) - ((n) * (m) * 16))
Yes - I wrote/write a lot of C programs and I did a lot of simple bit manipulations... just never had to write function-macros and hence the problem I encountered by not being able to declare a new variable in my "function"

4. You could always just go read the bitwise FAQ.

Quzah.

5. Come up with an algorithm for solving this instead of worrying about the coding.
In your post do you mean bit 5 or the 5th bit because there is a subtle difference.

6. Search the forum here for this; I answered this last week with a link to some C source that gives you easy to use macros for doing this...

7. Hi everyone....
I finally figured it out....

The proper wording of this problem is:
clear m bits starting at n-th location

#define CLEAR_BITS(reg_x, n, m) (reg_x | ~(2^m - 1) << n)

8. Originally Posted by v333k
clear m bits starting at n-th location

#define CLEAR_BITS(reg_x, n, m) (reg_x | ~(2^m - 1) << n)
Clearing bits needs the & operator, OR'ing would be used to set the bits.
So not sure if the CLEAR_BITS function macro does what it is intended for.

9. And 2^m is probably not what is intended either.

10. Originally Posted by tabstop
And 2^m is probably not what is intended either.
Oh yes - this is the not the XOR operator, it is the 2 to the power of m

11. Originally Posted by v333k
Oh yes - this is the not the XOR operator, it is the 2 to the power of m
You have that backwards. ^ is XOR. You may mean that you want power of 2, but that's not what you are doing.

Quzah.

12. Originally Posted by quzah
You have that backwards. ^ is XOR. You may mean that you want power of 2, but that's not what you are doing.

Quzah.
Correct - I meant the 2 to the power of m and not XOR