9
$\begingroup$

How can I convert a string containing a hex number such as "6b" to a hex digit that mathematica can use to do math with?

I have tried using ToExpression["6b"] but that just give me another string.

Note: Java's BigIntegerclass can construct hex integers from strings. Is there something like this in mathematica?

$\endgroup$
1
  • $\begingroup$ By the way, the returned value is not another string. It's the expression 6 b. If you do FullForm[ToExpression["6b"]] you will see its true form. One thing that makes Mathematica unusual as far as programming languages go is that unassigned symbols (like b in this case) have their own values. They aren't strings and they aren't "variables". They're symbols and they can be passed around like any other value. In Java-speak you can think of them as sort of like enums. $\endgroup$
    – amr
    Commented Sep 25, 2012 at 17:28

2 Answers 2

17
$\begingroup$

The function converting strings to integer is FromDigits. It is the counterpart of IntegerString and both functions can be used with whatever basis you like. Therefore, if you want to convert from base 16 you do

FromDigits["6b", 16]
$\endgroup$
1
  • $\begingroup$ And how could you take floating numbers? as FromDigits["5AF.D2", 16] $\endgroup$ Commented Oct 15, 2021 at 8:23
8
$\begingroup$
stringToHex[str_] := ToExpression["16^^" <> str];

This is just a way of automating the normal notation you would use, which is 16^^6b (check here for the documentation).

$\endgroup$
1
  • $\begingroup$ Your stringToHex function is converting a hexadecimal to decimal. The string argument passed contains the hex digits. Therefore, the name of the function should be changed to something like hexStringToDecimal. But this is already implemented with FromDigits[hexString, 16] as halirutan said. $\endgroup$ Commented Jun 20, 2015 at 0:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.