hexify.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /* vim: tabstop=4 shiftwidth=4 noexpandtab
  2. * This file is part of ToaruOS and is released under the terms
  3. * of the NCSA / University of Illinois License - see LICENSE.md
  4. * Copyright (C) 2018 K. Lange
  5. *
  6. * hexify - Convert binary to hex.
  7. *
  8. * This is based on the output of xxd.
  9. * Does NOT a hex-to-bin option - something to consider.
  10. */
  11. #include <stdio.h>
  12. #include <ctype.h>
  13. void print_line(unsigned char * buf, unsigned int width, unsigned int sizer, unsigned int offset) {
  14. fprintf(stdout, "%08x: ", sizer);
  15. for (unsigned int i = 0; i < width; ) {
  16. if (i >= offset) {
  17. fprintf(stdout, " ");
  18. } else {
  19. fprintf(stdout, "%02x", buf[i]);
  20. }
  21. i++;
  22. if (i == width) break; /* in case of odd width */
  23. if (i >= offset) {
  24. fprintf(stdout, " ");
  25. } else {
  26. fprintf(stdout, "%02x ", buf[i]);
  27. }
  28. i++;
  29. }
  30. fprintf(stdout, " ");
  31. for (unsigned int i = 0; i < width; i++) {
  32. if (i >= offset) {
  33. fprintf(stdout, " ");
  34. } else {
  35. if (isprint(buf[i])) {
  36. fprintf(stdout, "%c", buf[i]);
  37. } else {
  38. fprintf(stdout, ".");
  39. }
  40. }
  41. }
  42. fprintf(stdout, "\n");
  43. }
  44. int main(int argc, char * argv[]) {
  45. FILE * f;
  46. unsigned int width = 16; /* TODO make configurable */
  47. if (argc > 1) {
  48. f = fopen(argv[1], "r");
  49. if (!f) return 1;
  50. } else {
  51. f = stdin;
  52. }
  53. unsigned int sizer = 0;
  54. unsigned int offset = 0;
  55. unsigned char buf[width];
  56. while (!feof(f)) {
  57. unsigned int r = fread(buf+offset, 1, width-offset, f);
  58. offset += r;
  59. if (offset == width) {
  60. print_line(buf, width, sizer, offset);
  61. offset = 0;
  62. sizer += width;
  63. }
  64. }
  65. if (offset != 0) {
  66. print_line(buf, width, sizer, offset);
  67. }
  68. return 0;
  69. }