home *** CD-ROM | disk | FTP | other *** search
/ Programmer 7500 / MAX_PROGRAMMERS.iso / INFO / C / R_LA4_01.ZIP / BITCALC.C < prev    next >
Encoding:
C/C++ Source or Header  |  1987-12-23  |  2.3 KB  |  92 lines

  1. /* BITCALC.C - From page 345 of "Microsoft C Programming for    */
  2. /* the IBM" by Robert Lafore. It demonstrates the use of the    */
  3. /* 6 bitwise operators.  x1 and x2 were made unsigned int       */
  4. /* (different from book) to make the >> operator not insert     */
  5. /* a 1 in the leftmost bit.                                     */
  6. /****************************************************************/
  7.  
  8. #define TRUE 1
  9.  
  10. main()
  11. {
  12. char op[10];
  13. unsigned int x1, x2;
  14.  
  15.    while(TRUE) {
  16.       printf("\n\nEnter expression (example 'ff00 & 1111'): ");
  17.       scanf("%x %s %x", &x1, op, &x2);
  18.       printf("\n\n");
  19.       switch(op[0]) {
  20.          case '&':
  21.             pbin(x1);
  22.             printf("& (and)\n");
  23.             pbin(x2);
  24.             pline();
  25.             pbin(x1 & x2);
  26.             break;
  27.          case '|':
  28.             pbin(x1);
  29.             printf("| (incl or)\n");
  30.             pbin(x2);
  31.             pline();
  32.             pbin(x1 | x2);
  33.             break;
  34.          case '^':
  35.             pbin(x1);
  36.             printf("^ (excl or)\n");
  37.             pbin(x2);
  38.             pline();
  39.             pbin(x1 ^ x2);
  40.             break;
  41.          case '>':
  42.             pbin(x1);
  43.             printf(">> ");
  44.             printf("%d\n", x2);
  45.             pline();
  46.             pbin(x1 >> x2);
  47.             break;
  48.          case '<':
  49.             pbin(x1);
  50.             printf("<< ");
  51.             printf("%d\n", x2);
  52.             pline();
  53.             pbin(x1 << x2);
  54.             break;
  55.          case '~':
  56.             pbin(x1);
  57.             printf("~ (compliment)\n");
  58.             pline();
  59.             pbin(~x1);
  60.             break;
  61.          default:
  62.             printf("\nNot valid operator.\n");
  63.       }
  64.    }
  65. }
  66.  
  67. /* pbin */  /*prints number in hex and binary*/
  68. pbin(num)
  69. int num;
  70. {
  71. unsigned int mask;
  72. int j, bit;
  73.  
  74.    mask = 0x8000;                /*one-bit mask*/
  75.    printf("%04x  ", num);        /*print in hex*/
  76.    for(j = 0; j < 16; j++) {     /*for each bit in num*/
  77.       bit = (mask & num) ? 1 : 0;   /*bit is 1 or 0*/
  78.       printf("%d ", bit);
  79.       if (j == 7)
  80.          printf("-- ");
  81.       mask >>= 1;             /*shift mask right by 1 bit*/
  82.    }
  83.    printf("\n");
  84. }
  85.  
  86. /* pline */
  87. pline()
  88. {
  89.    printf("----------------------------------------\n");
  90. }
  91.  
  92.