In the program associated with the DS1821 thermometer / thermostat, the DS1821 status register was fetched and each bit was tested and ouput as illustrated.
if (status_setting & THF)
{
printf("THF = 1 ");
}
else
{
printf("THF = 0 ");
}
if (status_setting & TLF)
{
printf("TLF = 1 ");
}
else
{
printf("TLF = 0 ");
}
etc
This might have been implemented using the ? : construct;
printf("THF = %d", (status_setting & THF) ? 1 : 0);
printf("TLF = %d", (status_setting & TLF) ? 1 : 0);
Although the ? : at first appears cryptic, (my students avoid it like the plague), and it is probably no more efficient than the if then else, it sure saves a good deal of typing.
/* Program cond_1.c
**
** Prints a variable in binary format.
**
** This is implemented using the if-then-else construct
** and then the ? : construct.
**
** Note that a "1" in bit position is walked from left to right
** and each bit is tested in turn and either a "1" or "0" is output.
**
** copyright, Peter H. Anderson, Baltimore, MD, Oct, '00
*/
#include <stdio.h>
#include <conio.h>
typedef unsigned char byte;
void main(void)
{
byte val = 0x91;
signed char n;
clrscr();
for (n=7; n>=0; n--) /* do it the verbose way */
{
if (val & (0x01 << n))
{
printf("1");
}
else
{
printf("0");
}
}
printf("\n");
for (n=7; n>=0; n--) /* using the "dustier" ? : approach */
{
printf("%d", (val & (0x01 << n) ? 1 : 0));
}
printf("\n");
}