Re: Inverse of IntegerDigits? and "Index" function?

*To*: mathgroup at smc.vnet.net*Subject*: [mg3966] Re: Inverse of IntegerDigits? and "Index" function?*From*: danl (Daniel Lichtblau)*Date*: Mon, 13 May 1996 01:46:55 -0400*Organization*: Wolfram Research, Inc.*Sender*: owner-wri-mathgroup at wolfram.com

In article <4menl1$jva at dragonfly.wolfram.com> pehowland at taz.dra.hmg.gb () writes: > > Excuse me if I'm being particularly inept this morning, but can anyone offer > any help on the following problems please? > > Inverse of IntegerDigits > ======================== > I'm playing around with some binary numbers, and am using IntegerDigits > to convert from a decimal integer to the binary notation. eg. > In[1]:= IntegerDigits[10,2] > Out[1]= {1,0,1,0} > > What is the function to convert back? eg. I want to do > In[2]:= DigitsToInteger[{1,0,1,0},2] > and get > Out[2]= 10 > I've scoured the manual and can't find the function. This led me to > try to write my own function, which identified another problem... > > "Index" Function > ================ > Writing a function to convert back is easy in principle, eg. > > DigitsToInteger[x_,n_] := Apply[Plus[Map[(#*n^(Index[#]-1))&, Reverse[x]]]] > > would do the trick, but I seem to require a function, that I've called > Index[] here, that when Map[]'d across a list returns the position of > each element. Thus I want a function that works as follows: > > In[3]:= Map[Index[#]&, {2,6,3,9,10,2,4}] > Out[3]= {1,2,3,4,5,6,7} > > But I can't seem to find this function either! > > For the moment I'm using the following more Fortran-like function, which > works, but disturbs my sensibilities: > > DigitsToInteger[x_,n_] := > Module[{int=0, l}, > l = Reverse[x]; > Do [int = int + 2^(i-1)*l[[i]], > {i, Length[i]} > ]; > int > ] > > > Any suggestions? > > Paul E Howland Tel. +44 (0)1684 895767 > Long Range Ground Radar Sensors Fax. +44 (0)1684 896315 > LSC2 Division Email. PEHOWLAND at DRA.HMG.GB > Defence Research Agency > St Andrews Road > Malvern > Worcestershire, WR14 3PS, UK > ========================================================================= > Here are a couple of methods. The first is along the lines of your first attempt, the second is a more list-oriented way of doing the Hornering of your second method. In[13]:= DigitsToInteger1[x_List, base_Integer] := x.Table[base^k, {k,Length[x]-1,0,-1}] In[14]:= DigitsToInteger2[x_List, base_Integer] := Fold[(base*#1 + #2)&, 0, x] In[15]:= DigitsToInteger1[{1,0,1,0},2] Out[15]= 10 In[16]:= DigitsToInteger2[{1,0,1,0},2] Out[16]= 10 Daniel Lichtblau Wolfram Research, Inc. danl at wolfram.com ==== [MESSAGE SEPARATOR] ====