AnsweredAssumed Answered

What is the fastest way to test a bit?

Question asked by dww on Jul 15, 2011
Latest reply on Jul 25, 2011 by gpan



I often test bits in C using something like:


int result, value, bit;

result = value & (1 << bit);


Since I've been looking at the assembly this code generates I've seen the manual refer to a 'bit tst' instruction.  I'm less good with the assmbler but my guess is that the hardware can test a bit with one instruction.


The above code generates this:


r2=lshift r2 by r2, r0=m5;
r2=r2 and r2, i12=dm(m7,i6);


I've then seen this in the manual, which (not recommended) tests bit in system registers:


asm("R0 = 0; bit tst MODE1 IRPTEN; if TF r0 = r0 + 1; %0 = r0;"
: "=d"(test) : : "r0");


However, once I try this on my own values it refuses to compile.


I've got as far as changing it to:


int value, bit, result;
asm("r0 = 0; bit tst %1 %2; %0 = r0;" : "=d"(result) : "u"(value), "u"(bit));


but the assember fails to accept the %2 argument, although it does pass if I make a fixed number.  The error is


[Error ea1007] ".\Release\IgnoreChamber.s":26 [column 31] Syntax Error at ";".


with the code it generates


r0 = 0; bit tst ustat1 ustat1; r2 = r0;


Unfortunately I don't understand this enough to fix it.  Can user bits be tested with one instruction or am I waisting my time?  I'll happliy accept any tips on making testing a bit a little faster as I use this technique quite often.