Why doesn’t this work in Mathematica,
cu[x_] := BaseForm[2^^x, 16] ?
Why doesn’t this work in Mathematica,
cu[x_] := BaseForm[2^^x, 16] ?
what’s 2^^x ?
If I have the binary number, say, 1010, and type 2^^1010, then Mathematica will give me the value of the number in base 10. So, 2^^1010 will result in 10. Also, if I have 0xA and I type 16^^A then I will also get 10.
The reason (I think) is that “BaseForm is a wrapper that affects printing, but not evaluation” (as read from the documentation - similar to MatrixForm.). With that interpretation, we’re asking for BaseForm[wrapper, base], which I don’t think will evaluate.
Well, ok but I can enter, BaseForm[2^^1010,16] and get the correct answer.
Thanks.
The 2^^1010 immediately evaluates to 10, as seen from,
BaseForm[2^^1010,16]//FullForm (*Out[]:= BaseForm[10,16]*)
When we replace the 1010 with a symbol x, The outer wrapper BaseForm cannot immediately evaluate its argument in x, resulting in the expressions about incomplete expression. I see it similar to how we can’t add the following although the lists themselves will sum.
MatrixForm[{{3,2},{3,4}}]+MatrixForm[{{1,2},{3,4}}] (*Out[]:= Two matrices in textbook notation. *)
whereas,
{{3,2},{3,4}}+{{1,2},{3,4}}; (*Out[]:= {{4,4},{6,8}} *)
A sample solution tested on Mathematica 7 follows,
g[x_]:=(*This function takes a number-base-2 and returns its base-16*)
Module[{onesAt, argOne, ans},
(*Find where the ones are located in the input number-base-2*)
onesAt=Flatten[Position[IntegerDigits[x], 1(*EndPosition*)](*EndFlatten*)];
(*Convert the base 2 input to decimal.*)
argOne=Total[Power[2,#]&/@onesAt(*EndTotal*)];
ans=BaseForm[argOne,16]
(*EndModule*)];
Testing,
g[1010] (*Out[]:= a-subscript-16 *)