librfn
An ad-hoc utility library
hex.c
Go to the documentation of this file.
1 /*
2  * hex.c
3  *
4  * Part of librfn (a general utility library from redfelineninja.org.uk)
5  *
6  * Copyright (C) 2012 Daniel Thompson <daniel@redfelineninja.org.uk>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU Lesser General Public License as published
10  * by the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  */
13 
14 #include <ctype.h>
15 #include <stdlib.h>
16 #include <stdio.h>
17 #include <string.h>
18 
19 #include "librfn.h"
20 
21 static inline char hexchar(char h)
22 {
23  if (h < 10)
24  return '0' + h;
25 
26  return 'a' - 10 + h;
27 }
28 
29 int hex_dump_to_file(FILE *f, unsigned char *p, size_t sz)
30 {
31  size_t oldsz = sz;
32 
33  while (sz > 0) {
34  for (int i=0;
35  i<16 && sz > 0;
36  i++, sz--, p++)
37  fprintf(f, "%c%c", hexchar(*p >> 4), hexchar(*p & 0xf));
38  fprintf(f, "\n");
39  }
40 
41  return oldsz;
42 }
43 
44 int hex_dump(unsigned char *p, size_t sz)
45 {
46  return hex_dump_to_file(stdout, p, sz);
47 }
48 
49 static inline int nibble(char h)
50 {
51  if (h <= '9')
52  return h - '0';
53 
54  return (h & ~('a' - 'A')) - 'A' + 10;
55 }
56 
57 
58 int hex_get_byte(const char *s, const char **p)
59 {
60  next_line:
61  if (s) {
62  char *q = strchr(s, ':');
63  if (q)
64  s = q+1;
65  } else {
66  s = *p;
67  if (!s)
68  return -1;
69  }
70 
71  while (isspace((int) *s))
72  if (*s++ == '\n')
73  goto next_line;
74 
75  /* lazy evaluation ensures we don't read past end of string */
76  if ('0' == s[0] && 'x' == s[1])
77  s += 2;
78 
79  if (isxdigit((int) s[0]) && isxdigit((int) s[1])) {
80  *p = s + 2;
81  return 16 * nibble(s[0]) | nibble(s[1]);
82  }
83 
84  /* jump to the next line (if there is one) */
85  s = *p = strchr(s, '\n');
86  if (s++)
87  goto next_line;
88 
89  return -1;
90 }
int hex_dump_to_file(FILE *f, unsigned char *p, size_t sz)
Definition: hex.c:29
int hex_dump(unsigned char *p, size_t sz)
Definition: hex.c:44
int hex_get_byte(const char *s, const char **p)
Definition: hex.c:58