Code snippets:printing bits

From C

Jump to: navigation, search
/* Shao Miller - 2012-Oct-13 */

#include <stdio.h>

int main(void) {
    register unsigned char shift;
    register unsigned char * pos;
    unsigned char stream[] = { 1, 2, 3, 4 };
    register unsigned char * end;

    printf("Lowest-bit first: ");

    for (
        (shift = 1), (pos = stream), (end = stream + sizeof stream);
        pos < end;
        (shift <<= 1) ? 0 : (pos += ++shift)
      ) {
        printf((shift & *pos) ? "1" : "0");
      }

    printf("\n");

    printf("Lowest-bit first: ");

    shift = 1;
    pos = stream;
    end = stream + sizeof stream;
    while (pos < end) {
        printf((shift & *pos) ? "1" : "0");
        if (!(shift <<= 1))
          pos += ++shift;
      }

    printf("\n");

    return 0;
  }
Personal tools