Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project!

## bit testing in byte variable

Help
2008-12-04
2013-03-12

• Ronald Marcus
2008-12-04

Just a basic question about SDCC C.Can I test a bit with the following IF statement?

FOR(x=0;x<8;x++)//x will be a value between 0 and 7.
IF(test_byte,x) ybit = 1;
ELSE ybit = 0
I didn't know if the comma was the proper way to access a variable bit.
Thanks,
Ron

• Raphael Neider
2008-12-04

1. C is case sensitive, the keywords FOR, IF and ELSE must be all-lowercase (for, if, else).

2. No, you cannot access bits like that. You want
for (x=0; x<8; x++) {
if (test_byte & (1u << x)) ybit = 1;
else ybit = 0;
}

You might want a macro

#define BIT(byte, idx)  ((byte) & (1u << (idx)))

and use

if (BIT(test_byte, x)) { ybit = 1; }
else { ybit = 0; }

You might even want

for (x=0; x<8; x++) {
if (test_byte & mask) { ybit = 1; }
else { ybit = 0; }
}

or the probaly most efficient (except for unrolling the loop)

if (test_byte & mask) { ybit = 1; }
else { ybit = 0; }
}

This will loop over 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, and end on mask = 0x100 = 0x00 (mod 256), as mask is only 8 bit. I did not test this, though.

3. Assuming the code is not simplified, you might want to consider

ybit = (test_byte & 0x80) ? 1 : 0);

or

ybit = !!(test_byte & 0x80);

or

ybit = 0;
if (test_byte & 0x80) ybit = 1;

Good luck,
Raphael