4
$\begingroup$

How do we convert the BaseForm of 2 (binary data) to a set of number correspond to the their BaseForm in terms of an array.

For example,

Table[BaseForm[i, 2], {i, 0, 4}]

outputs

$${0_2,1_2,10_2,11_2,100_2}$$

How can we make the output to be:

{{0,0,0},{0,0,1},{0,1,0},{0,1,1},{1,0,0}}

Actually generally we need a larger set of data like

Table[BaseForm[i, 2], {i, 0, 2^8}]

so it is better to have a systematic method.

$\endgroup$
2
  • 1
    $\begingroup$ There's no reason to use BaseForm other than for display purposes, as far as I understand it. You would want to go back to the original numbers and use IntegerDigits, as suggested by @corey979. $\endgroup$
    – march
    Sep 29, 2016 at 16:49
  • $\begingroup$ in case you are stuck with it you can pull the number out as the first part of BaseForm , eg IntegerDigits[First@BaseForm[127, 2], 2, 8] -> {0, 1, 1, 1, 1, 1, 1, 1} $\endgroup$
    – george2079
    Dec 12, 2016 at 15:05

1 Answer 1

6
$\begingroup$

IntegerDigits is for this:

PadLeft[#, 3] & /@ Table[IntegerDigits[i, 2], {i, 0, 4}]

{{0, 0, 0}, {0, 0, 1}, {0, 1, 0}, {0, 1, 1}, {1, 0, 0}}


Thanks to march for pointing at the third argument of IntegerDigits that works like PadLeft:

Table[IntegerDigits[i, 2, 3], {i, 0, 4}]

{{0, 0, 0}, {0, 0, 1}, {0, 1, 0}, {0, 1, 1}, {1, 0, 0}}


But it has to be specified manually, so let's define

base2[n_] := Table[IntegerDigits[i, 2, Length@IntegerDigits[n, 2]], {i, 0, n}]

to return base-2 for numbers up to n in an automated manner. For example:

base2[10]

{{0, 0, 0, 0}, {0, 0, 0, 1}, {0, 0, 1, 0}, {0, 0, 1, 1}, {0, 1, 0, 0}, {0, 1, 0, 1}, {0, 1, 1, 0}, {0, 1, 1, 1}, {1, 0, 0, 0}, {1, 0, 0, 1}, {1, 0, 1, 0}}

and

base2[2^8]

also works.

$\endgroup$
1
  • 2
    $\begingroup$ It turns out IntegerDigits takes a third argument that specifies the padding: Table[IntegerDigits[i, 2, 3], {i, 0, 4}]. $\endgroup$
    – march
    Sep 29, 2016 at 16:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.