15

I'm trying to use baseform to convert numbers in base 10 to base n, how can I make the convertion between, say base 2 to base n?

Baseform seems to always think that the base in expr BaseForm[Expr, n] is always 10.

Red Banana
  • 5,329
  • 2
  • 29
  • 47

4 Answers4

22

It should be possible to use notation of the form base^^number inside the BaseForm expression like this:

BaseForm[2^^10101,14]

There are some similar examples under Properties and Relations in the documentation for BaseForm.

Verbeia
  • 34,233
  • 9
  • 109
  • 224
16

Here are the above elements wrapped up in function which pulls together the various, or user defined, output forms and lets you switch from any base to any base:

Clear[BaseTranslator];
Options[BaseTranslator] = {BTForm -> BaseForm};
BaseTranslator[number_, base1_, base2_, 
  OptionsPattern[]] := (OptionValue@BTForm)[
  FromDigits[ToString[number], base1], base2]

And some sample usage:

BaseTranslator[100,10,4]

12104

BaseTranslator[100, 10, 4 ,BTForm -> IntegerDigits]

{1, 2, 1, 0}

BaseTranslator[100, 2, 4, BTForm -> IntegerDigits]

{ 1, 0}

BaseTranslator[102, 10, 101, BTForm -> IntegerDigits]

{1, 1}

image_doctor
  • 10,234
  • 23
  • 40
10

Since numbers given in base^^ form automatically parse as regular number, it can be at times useful to pass numbers around as strings. For example:

FromDigits["100010011110011", 2]
17651

Different ways to represent that number:

IntegerDigits[17651, 16]

BaseForm[17651, 2]

IntegerString[17651, 2]

{4, 4, 15, 3}

1000100111100112

"100010011110011"

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
2

A simplest form for BaseTranslator (https://mathematica.stackexchange.com/users/776/image-doctor):

(*convert stringnumber from base1 to base2*)
convert[stringnumber_, base1_, base2_] :=    
  BaseForm[FromDigits[stringnumber, base1], base2]

convert["19a", 16, 10](*example 1*)

convert["A", 16, 2] (*example *)
 410

Subscript[1010, 2]

rosu_constantin
  • 121
  • 1
  • 6
  • ROSU, I formatted your code for you. Please see editing help to learn how to do this yourself. Also, I note that this answer has been down-voted; that is likely because it removes rather than adds functionality to image_doctor's method. – Mr.Wizard Jan 17 '14 at 15:33