NumPy base_repr writes an integer in another base without changing its value

The text 101 can mean different quantities depending on the base used to read it. A base label is part of the meaning, not decoration. Academia Master Trader presents this English lesson for readers in El Salvador, using NumPy base_repr to separate an integer's value from the string chosen to represent it.

Begin with the default binary representation

After import numpy as np, the call np.base_repr(5) returns the string '101'.

The default base is two. Reading those digits in binary gives one group of four, no groups of two and one unit, totaling five.

The function has not changed five into the decimal integer one hundred and one. It has produced text that represents five in a different positional number system.

That distinction matters when writing labels, exporting data or comparing a displayed representation with a value used in arithmetic.

The same integer can have different digit strings in different bases

A different base changes the digit positions

The call np.base_repr(6,base=5) returns '11'. In base five, the left digit contributes five and the right digit contributes one.

Likewise, np.base_repr(32,base=16) returns '20'. Two groups of sixteen and zero units describe the original decimal value thirty-two.

Each position has a weight determined by the base. Reading the output correctly requires keeping that base with the text.

The supported base range is two through thirty-six. Above base ten, letter symbols extend the available digits. For example, np.base_repr(10,base=16) returns 'A', and np.base_repr(35,base=36) returns 'Z'.

Padding adds zeros rather than setting a final width

NumPy's example np.base_repr(7,base=5,padding=3) returns '00012'.

Without padding, seven in base five is written as 12. The padding argument adds three zeros to the left of that representation.

It does not mean that the finished output must contain exactly three characters. In this example, the resulting string contains five digit characters.

Use that distinction when aligning labels. A request for a fixed overall field width is a different formatting rule from a request to add a specified number of zeros.

Negative output is signed text

The call np.base_repr(-5) returns '-101'. The leading minus sign accompanies a binary representation of the magnitude.

Do not interpret that string as a fixed-width two's-complement bit pattern. The function's output here is a signed textual representation, not a specification of machine storage.

The input parameter is an integer. The result is a string, so concatenating it with another string joins characters rather than adding numeric values.

Keep the original integer for calculations and use the representation for display or an explicitly defined text format.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Label the base whenever a digit string could otherwise be read ambiguously.