four2hex.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. Four2hex was written to convert the housecode based on digits ranging from 1
  3. to 4 into hex code and vica versa.
  4. Four2hex is freeware based on the GNU Public license.
  5. To built it:
  6. $ make four2hex
  7. Install it to /usr/local/bin:
  8. $ su
  9. # make install
  10. Here an example from "four"-based to hex:
  11. $ four2hex 12341234
  12. 1b1b
  13. Here an example in the other (reverse) direction:
  14. $ four2hex -r 1b1b
  15. 12341234
  16. Enjoy.
  17. Peter Stark, (Peter dot stark at t-online dot de)
  18. */
  19. #include <stdio.h>
  20. #include <ctype.h>
  21. int atoh (const char c)
  22. {
  23. int ret=0;
  24. ret = (int) (c - '0');
  25. if (ret > 9) {
  26. ret = (int) (c - 'a' + 10);
  27. }
  28. return ret;
  29. }
  30. int strlen(const char *);
  31. main (int argc, char **argv)
  32. {
  33. char c, *s, *four;
  34. long int result;
  35. int b, i, h;
  36. if (argc < 2 || argc >3) {
  37. fprintf (stderr, "usage: four2hex four-string\n");
  38. fprintf (stderr, " or: four2hex -r hex-string\n");
  39. return (1);
  40. }
  41. result = 0L;
  42. if (strcmp(argv[1], "-r") == 0) {
  43. /* reverse (hex->4) */
  44. for (s = argv[2]; *s != '\0'; s++) {
  45. c = tolower(*s);
  46. b = atoh(c);
  47. for (i = 0; i < 2; i++) {
  48. h = ((b & 0xc) >> 2) + 1;
  49. b = (b & 0x3) << 2;
  50. printf ("%d", h);
  51. }
  52. }
  53. printf ("\n");
  54. } else {
  55. /* normal (4->hex) */
  56. four = argv[1];
  57. if (strlen(four) == 4 || strlen(four) == 8) {
  58. for (s = four; *s != '\0'; s++) {
  59. result = result << 2;
  60. switch (*s) {
  61. case '1' : result = result + 0; break;
  62. case '2' : result = result + 1; break;
  63. case '3' : result = result + 2; break;
  64. case '4' : result = result + 3; break;
  65. default :
  66. fprintf (stderr, "four-string may contain '1' to '4' only\n");
  67. break;
  68. }
  69. }
  70. if (strlen(four) == 8) {
  71. printf ("%04x\n", result);
  72. } else {
  73. printf ("%02x\n", result);
  74. }
  75. } else {
  76. fprintf (stderr, "four-string must be of length 4 or 8\n");
  77. return (1);
  78. }
  79. }
  80. return (0);
  81. }