# Convert a string to hex number?

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?

-
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. – amr Sep 25 '12 at 17:28

## 2 Answers

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]

-
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).

-
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. – Athanassios Jun 20 at 0:22