/* This program illustrates the useful application of pointer arithmetics and unrestricted type casting in C. C is the default language for low level systems programming tasks. */ #include #include /* An ip address is represented as a 32 bit number. However, to make it meaningful to humans, we need to convert it into a readable form, such as "147.4.150.29". To do so we need to break the 32 bit value (represented as an int) into 4 byte-size chunks. Furthermore, we need to interpret each byte as an *unsigned* value, since the ip subnet numbers are from 0 to 255. */ // convert binary address to string form: char* unpack(int ip) { char *s = (char*)malloc(16); // max sizes needed for ip string rep. unsigned char * i = (unsigned char *)(&ip); sprintf(s, "%u.%u.%u.%u", *i,*(i+1),*(i+2),*(i+3)); return s; } // convert string representation to binary form: int pack(char* s) { int x; unsigned char ip[4]; sscanf(s, "%u.%u.%u.%u", ip,ip+1,ip+2,ip+3); x = *((int *)ip); // look ma, the array just became an int! return x; } int main(int argc, char** argv) { int ip = pack(*++argv); // ip string comes in as command-line arg. printf("binary representation is 0x%x\n",ip); //prints hexadecimal rep. char *sip = unpack(ip); printf("unpacked representation is %s\n",sip); free(sip); exit(0); } /* When was the last time you even used an "unsigned" type? If you haven't, then you've probably never done systems programming. That's OK, because most programmers operate at a higher level, using "application programmers' interfaces" (APIs) that abstracts away the need to deal with low-level representations. So then are the capabilities demonstrated here (cool, aren't they) consistent with the intended use of high-level, object-oriented software engineering languages? Indeed, you'd be silly to try to do serious systems programming in Java. On the other hand, what would happen if we carry-over these capabilities to include type casting over *objects*? You've already seen how my "A Poem in C++" program compromises the integrity of private variables. The following program offers a different example. */