I want to convert a hexadecimal string to a decimal (base 10) number:
16^^ff
16^^ToExpression["ff"]
The 1st line returns the correct answer of 255, while the 2nd line gives an error. Why doesn't it work?
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityAs already stated in the comments the ^^
notation is handled in parsing; observe:
HoldComplete[16^^ff] // FullForm
HoldComplete[255]
(I intend this to illustrate that this notation is "evaluated" before the main evaluator ever sees it.)
This parsing is really no different from other numerical notation in Mathematica, for example 12.345
is directly parsed as a Real
number, not an expression involving Dot
. Likewise 1*^6
is parsed as the Integer
one million, with no relation to Times
or Power
.
As Simon Woods recommended, for programmatic input of hexadecimals use FromDigits
:
FromDigits["ff", 16]
255
^^
corresponds toBaseForm
, although I grant you that this is referenced in theBaseForm
documentation. It is just another notation for entering numbers, like1*^10
. These particular notations are processed by the parser, are not interpreted as functions, and require that numeric literals appear both on the left and the right. It doesn't work sinceToExpression["ff"]
is not a numeric literal. You may use e.g.ToExpression@ToString@StringForm["16^^``", "ff"]
instead. $\endgroup$Accuracy[1.2``20]
$\endgroup$StringForm
's syntax... The second argument toStringForm
gets inserted where ever there's a double backtick. If you have more than one argument to insert, you can indicate the order with a number, like `1`. $\endgroup$ToExpression
but FYI the usual method to interpret a hexadecimal string is withFromDigits
, e.g.FromDigits["FF", 16]
gives 255 $\endgroup$