Logo  

CS456 - Systems Programming

Displaying exercises/e2/solution/hex.c

#include <stdio.h>
#include <unistd.h>
#include <stdint.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>


void prints(char *s) {
  write(STDOUT_FILENO, s, strlen(s));
}

void printc(char c) {
  write(STDOUT_FILENO, &c, 1);
}

void printbyte(uint8_t v) {
  char *hex = "0123456789ABCDEF";

  printc(hex[v>>4]);
  printc(hex[v&0x0F]);
}

void printdword(uint32_t v) {
  printbyte(v>>24 & 0xFF);
  printbyte(v>>16 & 0xFF);
  printbyte(v>> 8 & 0xFF);
  printbyte(v     & 0xFF);
}

int main(int argc, char *argv[])
{
  int fd = 0;
  int location = 0, r, i;
  uint8_t data[16];

  if (argc > 1) {
    fd = open(argv[1], O_RDONLY);
    if (fd < 0) {
      prints("Unable to open file");
      return 1;
    }
  }

  while((r = read(fd, data, 16)) > 0) {
    printdword(location);
    prints(": ");
    for(i = 0 ; i < r; i++) {
      printbyte(data[i]);
      printc(' ');
      if (i == 7) printc(' ');
    }
    for(i=r; i < 16; i++) {
      prints("   ");
      if (i == 7) printc(' ');
    }
    prints(": ");
    for(i=0; i < r; i++) {
      printc((isgraph(data[i]) || data[i] == ' ')? (char)data[i] : '.');
    }
    printc('\n');
    location += r;
  }
  return 0;
}