Re: Inverse of IntegerDigits? and "Index" function?
- To: mathgroup at smc.vnet.net
- Subject: [mg4006] Re: [mg3922] Inverse of IntegerDigits? and "Index" function?
- From: Robert Pratt <rpratt at math.unc.edu>
- Date: Tue, 14 May 1996 02:39:18 -0400
- Sender: owner-wri-mathgroup at wolfram.com
The following function, using Mma's built-in Table command, gives an inverse for IntegerToDigits. DigitsToInteger[x_, n_]:= Apply[Plus, Table[Reverse[x][[i]]*n^(i-1), {i, 1, Length[x]}]] Rob Pratt Department of Mathematics The University of North Carolina at Chapel Hill CB# 3250, 331 Phillips Hall Chapel Hill, NC 27599-3250 rpratt at math.unc.edu On Fri, 10 May 1996 pehowland at taz.dra.hmg.gb wrote: > > 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 > ========================================================================= > > ==== [MESSAGE SEPARATOR] ====