Base Conversion

+- HP Forums (http://www.hpmuseum.org/forum)
+-- Forum: HP Software Libraries (/forum-10.html)
+--- Forum: HP Prime Software Library (/forum-15.html)
+--- Thread: Base Conversion (/thread-6235.html)



Base Conversion - Stevetuc - 05-12-2016 01:46 AM

This program will convert between any base, with the user being prompted for the required output base.
It uses B→R() to first convert any base to decimal, then R→B() to convert to desired base:

Code:
EXPORT Baseconv(in)
BEGIN
LOCAL base,bits,sign;
CHOOSE(base, "Base", "System", "Binary","Octal","Decimal","Hex");
CHOOSE(bits, "Size","System","Input","8","16","32","64");
IF bits >2 THEN CHOOSE(sign, "Sign","Unsigned","Signed") END;
//IF LEFT(STRING(in),1) ≠ "#" THEN in:=EXPR("#"+in+"d") END; //correct the format - no longer needed
CASE
IF bits=1 THEN bits:=GETBITS(#) END //use system bitw
IF bits=2 THEN bits:=GETBITS(in) END //use input bitw
DEFAULT bits:=2^(bits)
END;
IF sign=2 THEN bits:=1-bits END;
SETBITS(SETBASE(in,base-1),bits); 
//R→B(B→R(in),bits,base-1) //old command
END;

I find it convenient to access via the Toolbox and User soft key.
I have hardcoded bits as 32. This could be set via another choose() or passed as Fn parameter.

If you prefer to access via a user key, it can be done like this:
Code:
KEY K_3()
BEGIN
"Baseconv()";
END;
I use key 3 because the shift # acts as mnemonic for Base.
Either method will work with rpn mode , so long as the input is already on the stack.

Updated to allow bitwidth to be chosen as Salvomic proposed, and also allow default system bitwidth option.

Numbers without # are treated as decimal - as suggested by Salvomic

Numbers with # but without explicit type are treated as per system setting for integers

Unsigned/Signed support - if width is selected as 8,16,32 or 64 a choose box for unsigned/signed is presented.
If Width is selected as System, then system setting for sign state is used.
If Width is selected as Input, then the input sign state is used.

Examples
( for this example system setting is hex 16bit unsigned)

Baseconv(#−9:-15d)
converted to binary 16 bit unsigned = #1111111111110111b

Baseconv(#−9:-15d)
Converted to binary 16bit signed= #−1001:-15b

Baseconv(#−9:-15d)
Converted to decimal 16bit unsigned = #65527d

In the first and last case, the size :16 is not explicitly shown because it matches the current system width. If the system width subsequently changes, then these will become explicit.

Steve