SOFTWARE IMPLEMENTATION OF AN ADC
     /* preliminaries */
     
     double dac(int* b, int B, double R);
     
     int u(double x) {
         if (x >= 0)
             {return 1;}
         return 0;
     }
     
     /* adc.c - successive approximation A/D converter */
     
     void adc(double x, int *b, int B, double R) {
     
     int i;
     double y, xQ, Q;
     
     Q = R / (double) (1 < < B);  // initialization
     y = x + Q/2;
     
     for (int i=0; i < B; i++)
        {b[i] = 0;}
     
     b[0] = 1 - u(y);	   // determine MSB
     
     for (int i=1; i < B; i++) {
        b[i] = 1;               // turn ith bit on
        xQ = dac(b, B, R);      // compute DAC output
        b[i] = u(y - xQ);       // test and correct bit
     }