# clearing bits using C macros

• 04-21-2010
v333k
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!
• 04-21-2010
whiteflags
Do you know any math or bitwise operators?

It could be something as simple as ((reg_x) - ((n) * (m) * 16))
• 04-21-2010
v333k
Quote:

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"

• 04-21-2010
quzah
You could always just go read the bitwise FAQ.

Quzah.
• 04-21-2010
itCbitC
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.
• 04-21-2010
jeffcobb
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...
• 04-22-2010
v333k
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)
• 04-22-2010
itCbitC
Quote:

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.
• 04-22-2010
tabstop
And 2^m is probably not what is intended either.
• 04-22-2010
v333k
Quote:

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
• 04-22-2010
quzah
Quote:

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.
• 04-23-2010
v333k
Quote:

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