Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!uwm.edu!spool.mu.edu!uunet!olivea!apple!amdahl!krs From: krs@uts.amdahl.com (Kris Stephens [Hail Eris!]) Newsgroups: comp.unix.shell Subject: Re: awk, how to convert hex to decimal Message-ID: <68Oa01JD19AR00@amdahl.uts.amdahl.com> Date: 5 Feb 91 19:20:49 GMT References: <23000@well.sf.ca.us> Reply-To: krs@amdahl.uts.amdahl.com (Kris Stephens [Hail Eris!]) Distribution: usa Organization: Amdahl Corporation, Sunnyvale CA Lines: 72 Here's the only semi-decent solution to this that *I* have found, which isn't to say there's not some way to get sprintf to handle it. # awk script to convert hex to decimal on output (an opcode in # chars 1 and 2 of $1) and display the indexed message tagged # by chars 2 and 3. # # Much much better idea to do this with C! BEGIN { # Set up the conversion-array Dec[] for ( i = 0; i <= 9; i++ ) Dec[i] = i Dec["A"] = 10 Dec["B"] = 11 Dec["C"] = 12 Dec["D"] = 13 Dec["E"] = 14 Dec["F"] = 15 Dec["a"] = 10 Dec["b"] = 11 Dec["c"] = 12 Dec["d"] = 13 Dec["e"] = 14 Dec["f"] = 15 # Message array Msg["0A"] = "This is message OA" Msg["0a"] = Msg["0A"] } { a = substr($1, 1, 1) b = substr($1, 2, 1) opcode = (16 * Dec[a]) + Dec[b] msgid = substr($1, 3, 2) # We won't use it, but what the heck -- convert msgid to decimal c = substr($1, 3, 1) d = substr($1, 4, 1) msgcode = (16 * Dec[c]) + Dec[d] printf("op(%d) id(%s): %s\n", opcode, msgid, Msg[msgid]) } By the way, a general-case conversion walks along a string, char by char (as mentioned in another article). Assuming that you want to convert the character-string hex number in $1 to decimal, and the Dec[] array has been defined as above... { a=0 for ( i = 1; i <= length($1); i++ ) { c = substr($1, i, 1) a = (16 * a) + Dec[c] } } and the variable 'a' has the decimal value of (hex) $1. The key to this is that each successive character requires the sum of all the previously evaluated characters to be multiplied by 16 (left-shift one char or four bits). For a four-char hex, char 1 is multiplied by 16 three times, char 2 twice, char 3 once, and char 4 not at all. ...Kris -- Kristopher Stephens, | (408-746-6047) | krs@uts.amdahl.com | KC6DFS Amdahl Corporation | | | [The opinions expressed above are mine, solely, and do not ] [necessarily reflect the opinions or policies of Amdahl Corp. ]