Re: Converting Binary form to a desired array

• To: mathgroup at smc.vnet.net
• Subject: [mg76026] Re: Converting Binary form to a desired array
• From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
• Date: Tue, 15 May 2007 04:46:57 -0400 (EDT)
• Organization: The Open University, Milton Keynes, UK
• References: <f2959d\$n0n\$1@smc.vnet.net>

```athlonspell wrote:
> Hello,
>
> I have this:
>
>>  BaseForm[212,2] = 10100
>
> Now, I am trying to achieve this output from above:
>
>>  {2^4, 0, 2^2, 0, 0}
>
> How do I go about do this?
>
> Thank you,
> Sharon

First, note that the binary representation of the decimal number 212 is
11010100 and not what you wrote (10100).

In[1]:=
BaseForm[212, 2]

Out[1]//BaseForm=
11010100
2

Second, BaseForm is just a wrapper (like NumberForm, PaddedForm, etc.).
You should use IntegerDigits to get a list that can be easily manipulated.

In[2]:=
IntegerDigits[212, 2]

Out[2]=
{1, 1, 0, 1, 0, 1, 0, 0}

The following function should do what you are looking for.

In[3]:=
myBase[n_Integer] := Module[{dg},
dg = IntegerDigits[n, 2];
Append[Reverse[MapIndexed[
If[#1 == 0, 0, HoldForm[2]^#2[[1]]] & ,
Reverse[Most[dg]]]], Last[dg]]]

In[4]:=
myBase[212]

Out[4]=
7   6      4      2
{2 , 2 , 0, 2 , 0, 2 , 0, 0}

Regards,
Jean-Marc

```

• Prev by Date: Re: Deleting duplicates from a list
• Next by Date: Re: HoldForm
• Previous by thread: Re: Converting Binary form to a desired array
• Next by thread: Re: Converting Binary form to a desired array