HP Forums
Convert Integers: Decimal to Any Base - Printable Version

+- HP Forums (https://www.hpmuseum.org/forum)
+-- Forum: HP Software Libraries (/forum-10.html)
+--- Forum: HP Prime Software Library (/forum-15.html)
+--- Thread: Convert Integers: Decimal to Any Base (/thread-7700.html)



Convert Integers: Decimal to Any Base - Eddie W. Shore - 02-02-2017 01:09 PM

Below are two programs that allow conversion of integers from decimal to any designated base. Integers used in base other than 10 are presented in list format. Each digit is separate and listed in order of descending place value.

For example: To input 1282_9 (base 9), enter {1, 2, 8, 2} and designate 9 as the base.

Digits are shown in numerical form and not in alphabetic. Hence, if you were working for hexadecimal, enter 10 for A, 11 for B, and so on.

HP Prime Program DEC2BASE

Code:
EXPORT DEC2BASE(N,B)
BEGIN
// decimal, base
// 2017-01-31 EWS
LOCAL S,L1,Q,D,X;
S:=IP(LN(N)/LN(B))+1;
L1:=MAKELIST(0,X,1,S);
D:=N;
FOR K FROM 1 TO S DO
Q:=IP(D/B^(S-K));
L1(K):=Q;
D:=D-Q*B^(S-K);
END;
RETURN L1;

END;

Convert 1254 to base 6.
Result: {5, 4, 5, 0} (5450_6).
(5 * 6^3 + 4 * 6^2 + 5*6)

Convert 17291 to base 13.
Result: {7, 11, 4, 1} (7B41_13)
(7 * 13^3 + 11 * 13^2 + 4 * 13 + 1)


HP Prime Program BASE2DEC

Code:
EXPORT BASE2DEC(L1,B)
BEGIN
// list of digits, base
// 2017-01-31 EWS
LOCAL S,N,K,Q;
S:=SIZE(L1);
N:=0;
FOR K FROM 1 TO S DO
N:=N+L1(K)*B^(S-K);
END;
RETURN N;
END;

Convert 4281_9 to decimal (4 * 8^3 + 2 * 9^2 + 8 * 9 + 1)
Input: {4, 8, 2, 1}, Base: 9
Result: 3583

Convert C107_16 to decimal (12 * 16^3 + 1 * 16^2 + 7)
Input: {12, 1, 0, 7}, Base: 16
Result: 49415