[PATCH] add hex en/decoding functions

Wilfried Goesgens <[email protected]>
Newsgroups gmane.comp.mobile.kannel.devel
Message-ID <[email protected]>
sometimes one must cope with converting numbers from hex to long, 
and vice versa. This is fine for the varous kinds of hex-pdus,
encoding and decoding them.


Wilfried Gösgens
add_hexfuncts.c.diff (text/plain, 1.2 KB)
--- a/gateway/gwlib/octstr.c	2006-03-17 11:19:43.000000000 +0100
+++ b/gateway/gwlib/octstr.c	2006-04-03 16:00:36.000000000 +0200
@@ -735,6 +737,54 @@
 }
 
 
+long octstr_hex_to_long(Octstr *ostr, int start, int end)
+{
+	int i;
+	long ret=0;
+	
+	/* if the string is too long, not *2 because of we aren't signed. */
+	if (end==0) end=ostr->len;
+	/* this is bullshit.	gw_assert(sizeof(long)<(end-start)); */
+	
+
+	for(i=start; i<end; i++)
+		{
+			int hexc=0;
+			/* 0-9 */
+			hexc= toupper(ostr->data[i]) - 48;
+			/* A-F ? */
+			if (hexc > 9)
+				hexc -= 7;
+			/* none of the above? */
+			if ((hexc < 0) || (hexc > 15))
+				return -1;
+			ret=(ret<<4)|hexc;
+		}
+    /* success */
+	return ret;
+
+}
+
+Octstr *octstr_long_to_hex(long data, long digits)
+{
+#define FIELDLEN 255
+	long resi, rest, n;
+	char ch[FIELDLEN+1]; /* the \0 */
+
+	rest=data;
+	ch[FIELDLEN+1]='\0';
+	for (n=0; n<digits; n++)
+		{
+			resi=data%16;
+			if (resi >9)
+				ch[FIELDLEN-n]=55+resi;
+			else 
+				ch[FIELDLEN-n]=(char)48+resi;
+			data=data/15;
+		}
+	return octstr_create(&ch[FIELDLEN-digits+1]);
+}
+
 long octstr_parse_long(long *nump, Octstr *ostr, long pos, int base)
 {
     /* strtol wants a char *, and we have to compare the result to
add_hexfuncts.h.diff (text/plain, 948 B)
--- a/gateway/gwlib/octstr.h	2006-02-23 02:25:17.000000000 +0100
+++ a/gateway/gwlib/octstr.h	2006-04-03 15:51:01.000000000 +0200
@@ -266,6 +265,19 @@
  * encoding defined in RFC 2045. */
 void octstr_base64_to_binary(Octstr *ostr);
 
+/* Parse a hex ascii encoded number to its corrosponding long value 
+ * start: where to start searching 
+ * end: where to end searching. if 0 set to the length of octstr
+ */
+long octstr_hex_to_long(Octstr *ostr, int start, int end);
+
+/* convert a long value to a hexadecimal representation. 
+ * data is the number to print, digits is the number of
+ * digits that will be used in the string. 
+ * it works right to left, so the decimal point is the anchor 
+ * digits is counted from. larger values will be cut.
+ */
+Octstr *octstr_long_to_hex( long data, long digits);
 
 /* Parse a number at position 'pos' in 'ostr', using the same rules as
  * strtol uses regarding 'base'.  Skip leading whitespace.
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.