summaryrefslogtreecommitdiffstats
path: root/src/lib.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/lib.c')
-rw-r--r--src/lib.c39
1 files changed, 39 insertions, 0 deletions
diff --git a/src/lib.c b/src/lib.c
new file mode 100644
index 0000000..891fd27
--- /dev/null
+++ b/src/lib.c
@@ -0,0 +1,39 @@
+/**
+ * writes a hexadecimal representation of a binary string. does not NULL terminate destination.
+ *
+ * h and b may not overlap. period.
+ *
+ * @param h [out] destination (requires 2l space)
+ * @param b [in] source
+ * @param l [in] length of source
+ */
+
+void bin2hex (char * h, const unsigned char * b, size_t l) {
+ for (size_t i = 0; i < l; i++) {
+ int ms = b[i] >> 4;
+ int ls = b[i] & 0xF;
+ assert(ms < 16);
+ assert(ls < 16);
+ *h++ = ms < 10 ? '0'+ms : 'a'+ms-10;
+ *h++ = ls < 10 ? '0'+ls : 'a'+ls-10;
+ }
+}
+
+/**
+ * converts a hexadecimal string to bytes
+ *
+ * b and h may not overlap, unless they are the same address
+ *
+ * @param b [out] array of bytes to write to with capacity l
+ * @param h [in] array of hex to read from with 2l hex digits
+ * @param l [in] length of output array
+ */
+
+void hex2bin (unsigned char * b, const char * h, int l) {
+ for (int i = 0; i < l; i++) {
+ char ms = *h++;
+ char ls = *h++;
+ b[i] = (ms >= 'a' ? ms - 'a' + 10 : (ms >= 'A' ? ms - 'A' + 10 : ms - '0')) << 4;
+ b[i] |= (ls >= 'a' ? ls - 'a' + 10 : (ls >= 'A' ? ls - 'A' + 10 : ls - '0'));
+ }
+}