Simple utilities sink - stuff that doesn't fit anywhere else / objects in plain C Snapshot
|
00001 #include <stdio.h> 00002 #include <stdlib.h> 00003 #include <string.h> 00004 #include <malloc.h> 00005 #include <ctype.h> 00006 #include <stdint.h> 00007 #include "hex.h" 00008 00009 #define HEX_LINE_LENGTH 16 00010 00011 char *make_hex_dump(const char *data, size_t len) 00012 { 00013 int lines = (len / HEX_LINE_LENGTH) + 1; 00014 char *buf = malloc( lines * ( HEX_LINE_LENGTH * 3 + HEX_LINE_LENGTH + 2 ) + 2 ); 00015 size_t i,j,k,ch,nl ; 00016 int cc; 00017 00018 ch = 0; 00019 00020 for(i = 0; i < len; ) { 00021 nl = j = i + HEX_LINE_LENGTH; 00022 if (j > len) { 00023 j = len; 00024 } 00025 00026 for(k=i ; k < j; k++) { 00027 sprintf(buf + ch, "%02x ", (unsigned char) data[k] ); 00028 ch += 3; 00029 } 00030 00031 for( ; k < nl ; k ++ ) { 00032 sprintf(buf + ch, " "); 00033 ch += 3; 00034 } 00035 00036 00037 buf[ch++] = ' '; 00038 00039 for(k=i; k < j; k++) { 00040 cc = data[ k ]; 00041 if ( isprint( cc ) ) { 00042 buf[ch++] = data[k]; 00043 } else { 00044 buf[ch++] = '.'; 00045 } 00046 } 00047 00048 i = j; 00049 buf[ch++] = '\n'; 00050 } 00051 buf[ch] = '\0'; 00052 00053 return buf; 00054 } 00055 00056 void *parse_hexa_string( const char *str, int len, uint32_t *rsize ) 00057 { 00058 uint8_t * buf, *pos; 00059 int low_val, high_val; 00060 char ch; 00061 00062 if (len == -1) { 00063 len = strlen( str ); 00064 } 00065 00066 buf = (uint8_t *) malloc( len ); 00067 if (!buf) { 00068 return 0; 00069 } 00070 00071 00072 for( pos = buf ; *str != '\0'; ++str) { 00073 ch = *str; 00074 if (ch >= 'a' && ch <= 'z') { 00075 high_val = (ch - 'a') + 10; 00076 } else if (ch >= 'A' && ch <= 'Z') { 00077 high_val = (ch - 'A') + 10; 00078 } else if (ch >= '0' && ch <= '9') { 00079 high_val = (ch - '0'); 00080 } else { 00081 goto err; 00082 } 00083 ++str; 00084 00085 if (*str != '\0') { 00086 ch = *str; 00087 if (ch >= 'a' && ch <= 'z') { 00088 low_val = (ch - 'a') + 10; 00089 } else if (ch >= 'A' && ch <= 'Z') { 00090 low_val = (ch - 'A') + 10; 00091 } else if (ch >= '0' && ch <= '9') { 00092 low_val = (ch - '0'); 00093 } else { 00094 goto err; 00095 } 00096 } else { 00097 high_val = 0; 00098 } 00099 00100 *pos++ = (uint8_t) ( (high_val << 4) | low_val ); 00101 } 00102 00103 *rsize = pos - buf; 00104 return buf; 00105 err: 00106 return 0; 00107 } 00108 00109 00110