2
|
6075 Views
|
3 Replies
|
5 Total Likes
View groups...
Share
GROUPS:

To Hex and Back Again

Posted 11 years ago
 I come from a (spit, spit!) Windows programming background, and am just getting my head around Mathematica.Although I am happy to do most things "the Wolfram Way", it does seem to me that certain habits might be kept. One I miss a lot is the rich range of named colours that Windows and HTML/CSS provide. One example: Firebrick, which takes a Hex value of B22222.So I thought of writing a hex to decimal converter.I understand this works at the Mathematica prompt:16^^B2...but if I write a function, thus:hexToDecimal[hex_] := 16^^hex...then evalutate...hexToDecimal[B2]...it complains that "h" is too large a value. It is not matching "hex" to the value supplied in the function.Any ideas how I can get round this?BaseForm[] does seem to do the job either.Thanks in advance.Brad
3 Replies
Sort By:
Posted 11 years ago
 I think the problem is that (from Mma 7 documentation),BaseForm acts as a \[OpenCurlyDoubleQuote]wrapper\[CloseCurlyDoubleQuote], which affects printing, but not evaluation. One may have to implement the conversion using a formula. The following is my solution which does the job for hex >= 0. Most of the code is just annotation with 5 lines that do any real work. Even those lines can be wrapped into one another to create a more concise function, probably at the cost of readability.  (* iabraham, Mathematica 7.0.1.0, Win-7-64b *) Clear["Global`*"];  h2d[hex_] := Module[{dictionary = { A -> 10, B -> 11, C -> 12, D -> 13, E -> 14, F -> 15}}, {(* Begin Module body. *) (* Convert the hex into its digits, and replace A, B, C.... with decimal values from the dictionary. *) stringInHex = Characters[ ToString[hex] ]; valuesInHex = ToExpression[stringInHex] /. dictionary;(* Debug print. *)(* Print[ "String in hex = ", stringInHex];Print[ "Values in hex = ", valuesInHex];*)(* Generate the weight-table based on length of hex digits. *)weights = Table[ Power[16,i],{i, Length[valuesInHex] - 1, 0, -1}];(* Debug print. *)(*Print[" Weights list = ", weights];*)values = ToExpression[valuesInHex] weights;decimal = Total[values](* End Module body. *)}(* End Module. *)]
Posted 11 years ago
 Could also use built-in functions:In[1]:= FromDigits["B2", 16]Out[1]= 178In[2]:= IntegerString[%, 16] // ToUpperCaseOut[2]= "B2"
Posted 11 years ago
 Thanks, Ilian, that's done it perfectly.
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.