039 bindump

#include <stdio.h>

void dump_bits(unsigned char *addr, size_t size)
{
  char buf[256];
  int j, buflen;
  while (size > 0)
  {
    int head = size % 4;
    if (head == 0)
    {   
      // print Bit position, like B32 B31 B30 ...
      buflen = 0;
      for (j = size*8; j > size*8-32; j--)
        buflen += snprintf(buf+buflen, sizeof(buf), "|B%2d", j-1);
      printf("%s\n", buf);
      // print upper seperator(-) with same length with Bit position
      for (j = buflen; j > 0; j--) printf("-");
      printf("\n");
      // print Bit value
      j = 32; 
      while (j--) printf("|% 3d", ((*(addr+size-4+j/8) >> j%8) & 0x01));
      printf("\n");
      // print lower seperator(-) with same length with Bit position
      for (j = buflen; j > 0; j--) printf("-");
      printf("\n");
      size -= 4;
    }   
    else // the size of object is not times of 4 bytes, print the head
    {   
      // print Bit position, like B32 B31 B30 ...
      buflen = 0;
      for (j = size*8; j > 0; j--)
        buflen += snprintf(buf+buflen, sizeof(buf), "|B%2d", j-1);
      printf("%s\n", buf);
      // print upper seperator(-) with same length with Bit position
      for (j = buflen; j > 0; j--) printf("-");
      printf("\n");
      // print Bit value
      j = head * 8;
      while (j--) printf("|% 3d", ((*(addr+size-head+j/8) >> j%8) & 0x01));
      printf("\n");
      // print lower seperator(-) with same length with Bit position
      for (j = buflen; j > 0; j--) printf("-");
      printf("\n");
      size -= head;
    }   
  }
}

int main(int argc, char *argv[])
{
  size_t size;

  char c = 'a';
  size = sizeof(c);
  printf("<< char(%ld bytes, value %d) >>\n", size, c);
  dump_bits((unsigned char *)&c, size);

  int i = 2;
  size = sizeof(i);
  printf("<< int(%ld bytes, value %d) >>\n", size, i);
  dump_bits((unsigned char *)&i, size);

  short s = 10;
  size = sizeof(s);
  printf("<< short(%ld bytes, value %d) >>\n", size, s);
  dump_bits((unsigned char *)&s, size);

  long int l = 65L;
  size = sizeof(l);
  printf("<< long(%ld bytes, value %ld) >>\n", size, l);
  dump_bits((unsigned char *)&l, size);

  long long ll = 130LL;
  size = sizeof(ll);
  printf("<< long long(%ld bytes, value %lld) >>\n", size, ll);
  dump_bits((unsigned char *)&ll, size);

  float f = 1.5;
  size = sizeof(f);
  printf("<< float(%ld bytes, value %.2f) >>\n", size, f);
  dump_bits((unsigned char *)&f, size);

  double d = 9.9;
  size = sizeof(d);
  printf("<< double(%ld bytes, value %.2f) >>\n", size, d);
  dump_bits((unsigned char *)&d, size);

  return 0;
}