Conversion to Binary and IEEE-754 Binary
08-02-2020, 02:51 PM (This post was last modified: 08-02-2020 02:52 PM by Eddie W. Shore.)
Post: #5
 Eddie W. Shore Senior Member Posts: 1,448 Joined: Dec 2013
RE: Conversion to Binary and IEEE-754 Binary
Here is my second attempt at it, except I just concentrated at the conversion to binary, with a user-given precision level.

To help with rounding the number, I first round the number to the nearest 1/2^n, then convert the result to binary.

I have not retried the IEEE-754 yet.

The program RBIN converts any real number in base 10 to base 2, including non-integers and negative numbers. The result is displayed as a string.

RBIN will need two arguments: the number to be converted and the precision level.

For the precision level:

1 rounds the number to the nearest 1/2 before conversion.

2 rounds the number to the nearest 1/4 before conversion.

3 rounds the number to the nearest 1/8 before conversion.

4 rounds the number to the nearest 1/16 before conversion.

and so on.

HP Prime Program: RBIN

Code:
EXPORT RBIN(x,p) BEGIN // 2020-07-11 EWS // Decimal to Binary // decimal, precision // for real x, rounded 1/2^p LOCAL b,i,f,n,s,w,k,str; s:=ABS(x); b:=IP(s)+ROUND(FP(s)*2^p,0)/2^p; str:=""; i:=IP(b); f:=FP(b); IF i≠0 THEN n:=IP(LOG(i)/LOG(2)); FOR k FROM n DOWNTO 0 STEP 1 DO w:=IP(i/2^k); str:=str+STRING(w); i:=i-w*2^k;  END; END; IF f≠0 THEN str:=str+"."; FOR k FROM 0 TO p-1 DO w:=IP(2*f); str:=str+STRING(w); f:=FP(2*f); END; END; IF x<0 THEN str:="-"+str; END; RETURN str; END;

Examples:

RBIN(-0.985,3) returns "-1"
RBIN(-0.985,6) returns "-.111111"
RBIN(-0.985,9) returns "-.111111000"

RBIN(860.63,3) returns "1101011100.101"
RBIN(860.63,6) returns "1101011100.101000"
RBIN(860.63,9) returns "1101011100.101000011"