Message Boards Message Boards

3 Replies
5 Total Likes
View groups...
Share this post:

To Hex and Back Again

Posted 10 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:


...but if I write a function, thus:

hexToDecimal[hex_] := 16^^hex

...then evalutate...

hexToDecimal[B2] 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.

POSTED BY: Brad Varey
3 Replies
Posted 10 years ago
Thanks, Ilian, that's done it perfectly. 
POSTED BY: Brad Varey
Could also use built-in functions:
In[1]:= FromDigits["B2", 16]
Out[1]= 178
In[2]:= IntegerString[%, 16] // ToUpperCase
Out[2]= "B2"
POSTED BY: Ilian Gachevski
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, Win-7-64b *)
 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 BY: Isaac Abraham
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract