9511_workbook

solved exercises from algorithms & programming I (9511) prof. Cardozo
Index Commits Files Refs README
guia07/ex07.c (750B)
   1 #include <stdio.h>
   2 
   3 #define MASK_POWER        0x80
   4 
   5 #define SHIFT_POWER        7
   6 
   7 typedef unsigned char uchar;
   8 typedef enum { OK, ERROR_NULL_POINTER } status_t;
   9 
  10 void print_reg(unsigned char reg);
  11 status_t toggle_bit(uchar *reg, uchar shift);
  12 
  13 int main (void)
  14 {
  15     /* 0000 0000 */
  16     uchar reg = 0x00;
  17     print_reg(reg);
  18 
  19     if(toggle_bit(&reg, SHIFT_POWER)) return ERROR_NULL_POINTER;
  20     print_reg(reg);
  21 
  22     if(toggle_bit(&reg, SHIFT_POWER)) return ERROR_NULL_POINTER;
  23     print_reg(reg);
  24     return 0;
  25 }
  26 
  27 void print_reg(uchar reg)
  28 {
  29     for(size_t i = ((sizeof(reg) * 8)); i > 0; i--)
  30         putchar((reg & (0x01 << (i - 1))) ? '1' : '0');
  31 
  32     putchar('\n');
  33 }
  34 
  35 status_t toggle_bit(uchar *reg, uchar shift)
  36 {
  37     if(!reg) return ERROR_NULL_POINTER;
  38 
  39     *reg ^= (0x01 << shift);
  40 
  41     return OK;
  42 }