#include "Csapp.h"/* This code converts IP addresses in dotted decimal form to hexadecimal numbers and outputs *///returns a String representing the integer int str2int (char *str) { //to notice the initialization of a variable int value=0; //string length int length = strlen (str); //radix int base=1; while (--length!=0) { base*=10; } while (*str!= ') { //is calculated using ASCII code int c = *str++; value = value + (c - 48) * base; base/=10; } return value;} Converts a decimal integer to a 16-hexadecimal integer and outputs char base_10_to_base_16 (int value) { if (value>=0&&) as a character value<=9) return (value+48); else if (value>=10&& value<=15) return (value-10+97);} Converts an array of 16 binary integers into a string output, calling the Base_10_to_base_16 function above char* int_to_string_of_Base_16 (int value[],int bit) { char* str = (char *) malloc (sizeof (char) *2*bit); char* copy_str = str; int i; for (i=0;i<bit;i+ +) { int bit_1 = value[i]/16; int bit_2 = value[i]%16; *str++ = base_10_to_base_16 (bit_1); *str++ = base_10_to_base_16 (bit_2); } return copy_str;} Main function Void main (int argc,char* argv[]) { if (argc<2) { printf ("input error!you should input like this:%s 172.20.4.163\n", argv[0]); exit (0); } //Note that hex may be 4-bit or 6-bit, dynamic change char *hex=argv [1]; //Initial number of 1 int bit_length = 1; while (*hex!= ') ) { if (*hex++== '. ') bit_length++; } int value[bit_length]; //counter int count = 0; int index = 0; char *s = argv[1]; char *old = argv[1]; char ch; while (*old!= ') { if (*old++== '. ') { s[count]= ' + '; value[index++] = str2int (s); s=old; count = 0; } else count+ +; if (* (old+1) = = ' + ') value[index++] = Str2Int (s); } //output conversion result printf ("0x%s\n", int_to_string_of_base_16 (value, bit_length)); exit (0);}
Convert IP address to hexadecimal number in dotted decimal form