libswarm-ng

C implementation of BMT hasher, Swarmhash and Single Owner Chunk for swarm
git clone git://git.defalsify.org/libswarm-ng.git
Log | Files | Refs | Submodules | README

hex.c (1183B)


      1 #include <string.h>
      2 #include <stdio.h>
      3 #include <stdlib.h>
      4 
      5 #include "hex.h"
      6 
      7 /**
      8 * \todo improve
      9 */
     10 int toHex(const unsigned char *data, size_t l, unsigned char *zHex, size_t *z) {
     11 	int i;
     12 	
     13 	if (*z < (l*2)+1) {
     14 		return 1;
     15 	}
     16 
     17 	for (i = 0; i < l; i++) {
     18 		sprintf(zHex+(i*2), "%02x", *(data+i));
     19 	}
     20 	*z = (i*2);
     21 	*(zHex+(*z)) = 0x0;
     22 	*z++;
     23 	return 0;
     24 }
     25 
     26 
     27 // cheekily stolen from https://nachtimwald.com/2017/09/24/hex-encode-and-decode-in-c/
     28 int hexchr2bin(const char hex, char *out) {
     29 	if (out == NULL)
     30 		return 0;
     31 
     32 	if (hex >= '0' && hex <= '9') {
     33 		*out = hex - '0';
     34 	} else if (hex >= 'A' && hex <= 'F') {
     35 		*out = hex - 'A' + 10;
     36 	} else if (hex >= 'a' && hex <= 'f') {
     37 		*out = hex - 'a' + 10;
     38 	} else {
     39 		return 0;
     40 	}
     41 
     42 	return 1;
     43 }
     44 
     45 size_t hex2bin(const char *hex, unsigned char *out) {
     46 	size_t len;
     47 	char   b1;
     48 	char   b2;
     49 	size_t i;
     50 
     51 	if (hex == NULL || *hex == '\0' || out == NULL)
     52 		return 0;
     53 
     54 	len = strlen(hex);
     55 	if (len % 2 != 0)
     56 		return 0;
     57 	len /= 2;
     58 
     59 	memset(out, 'A', len);
     60 	for (i=0; i<len; i++) {
     61 		if (!hexchr2bin(hex[i*2], &b1) || !hexchr2bin(hex[i*2+1], &b2)) {
     62 			return 0;
     63 		}
     64 		//(*out)[i] = (b1 << 4) | b2;
     65 		*(out+i) = (b1 << 4) | b2;
     66 	}
     67 	return len;
     68 }