Reputation:
compiler: IAR platform: stm32f4
i have this code but it dont work as expected. some one can explain me why?
#define byteGetbit(x,y) ((x) & (0x01 << (y)))
volatile t_uint8 test=0xFF;
if(byteGetbit(test,0x03)==1){ //always false
printf("hello"); //can't reach the code here
test = 0;
}
workaround:
if(byteGetbit(test,0x03)){
printf("hello");
test = 0;
}
Upvotes: 0
Views: 437
Reputation: 3453
You don't read the bit, but you isolate the bit at it's current locations.
You should change byteGetbit to this:
#define byteGetbit(x,y) ((x >> y) & 0x01)
This will shift the bit to bit 0 and then isolate it.
Upvotes: 0
Reputation: 21223
((x) & (0x01 << (y)))
is not a logical operation, thus, it does not yield a 0 or 1 result. In this particular example, ((x) & (0x01 << (y)))
results in 0 (for the case that bit y
is disabled in x
, or it results in a binary number with only bit y
set, which can be 1 (if y == 0
), but it doesn't have to be 1 (and it never is for the case that y
> 0).
If you want byteGetbit
to evaluate to either 1 or 0, like logical operations, you should use this instead:
#define byteGetbit(x,y) (((x) & (0x01 << (y))) ? 1 : 0)
This will evaluate to 1 if bit y
is set on x
and to 0 otherwise. In other words, it gives you the value of the y
-th bit on x
.
Upvotes: 1
Reputation: 145889
byteGetbit
yields a value with the corresponding bit set or clear, so to test for the bit set you have to either check:
if(byteGetbit(test,0x03) == 0x03)
or
if(byteGetbit(test,0x03)) // test if byteGetbit(test,0x03) != 0
Upvotes: 2