liblash

Basic tools written and used by lash in c programming.
Info | Log | Files | Refs

hex.c (1282B)


      1 char *_x = "0123456789abcdef";
      2 
      3 void b2c(char in, char *out) {
      4 	int v;
      5 
      6 	v = (in & 0xf0) >> 4;
      7 	*out = *(_x+v);
      8 	v = in & 0x0f;
      9 	*(out+1) = *(_x+v);
     10 }
     11 
     12 void b2h(const unsigned char *in, int l, unsigned char *out) {
     13         int i;
     14 	char *p;
     15 
     16 	p = (char*)out;
     17         for (i = 0; i < l; i++) {
     18 		b2c(*(in+i), p);
     19 		p += 2;
     20 	}
     21 	*p = 0;
     22 }
     23 
     24 char* c2h(char in, char *out) {
     25 	char i;
     26 	i = in & 0x0f;
     27 	*(out+1) = *(_x+i);
     28 	in >>= 4;
     29 	i = in & 0x0f;
     30 	*out = *(_x+i);
     31 	return out;
     32 }
     33 
     34 int n2b(const char in, char *out) {
     35 	if (out == 0x0) {
     36 		return 1;
     37 	}
     38 
     39 	if (in >= '0' && in <= '9') {
     40 		*out = in - '0';
     41 	} else if (in >= 'A' && in <= 'F') {
     42 		*out = in - 'A' + 10;
     43 	} else if (in >= 'a' && in <= 'f') {
     44 		*out = in - 'a' + 10;
     45 	} else {
     46 		return 1;
     47 	}
     48 
     49 	return 0;
     50 }
     51 
     52 int h2b(const char *in, unsigned char *out) {
     53 	int r;
     54 	int i;
     55 	char b1;
     56 	char b2;
     57 	char *po;
     58 	char *pi;
     59 
     60 	if (in == 0x0 || *in == '\0' || out == 0x0) {
     61 		return 0;
     62 	}
     63 
     64 	i = 0;
     65 	po = (char*)out;
     66 	pi = (char*)in;
     67 	while (1) {
     68 		if (*pi == 0) {
     69 			break;
     70 		}
     71 		r = n2b(*pi, &b1);
     72 		if (r) {
     73 			return 0;
     74 		}
     75 		pi++;
     76 		if (*pi == 0) { // we dont allow cut strings
     77 			return 0;
     78 		}
     79 		r = n2b(*pi, &b2);
     80 		if (r) {
     81 			return 0;
     82 		}
     83 		pi++;
     84 
     85 		//(*out)[i] = (b1 << 4) | b2;
     86 		*po = (b1 << 4) | b2;
     87 		po++;
     88 		i++;
     89 	}
     90 	return i;
     91 
     92 }