|
IEEE754 浮動小数変換
正規化数のみ対応 (非正規化数、無限大、NaN値には対応していません)
OPTION CHARACTER BYTE
LET X=1/3
PRINT CVS(FLOAT2STR$(X,8,23)) !'float 32bit
PRINT STR2FLOAT(PACKDBL$(X),11,52) !'double 64bit
PRINT STR2FLOAT(FLOAT2STR$(X,15,64),15,64) !'long double 80bit
END
EXTERNAL FUNCTION AND(X,Y)
LET XO=X
LET YO=Y
LET A=1
LET S=0
FOR I=0 TO 31
LET XX=MOD(XO,2)
LET YY=MOD(YO,2)
IF YY+XX=2 THEN LET S=S+A
LET XO=INT(XO/2)
LET YO=INT(YO/2)
LET A=A*2
NEXT I
LET AND=S
END FUNCTION
EXTERNAL FUNCTION CVS(A$)
!'IEEE754 32bit str to float
OPTION CHARACTER BYTE
OPTION BASE 0
DIM B(32)
LET A$=LEFT$(A$,4)
LET K = 0
FOR I = 4 TO 1 STEP -1
LET D$ = MID$(A$, I, 1)
FOR J = 0 TO 7
IF AND(ORD(D$),2 ^ (7 - J))<>0 THEN LET B(K) = 1 ELSE LET B(K) = 0
LET K = K + 1
NEXT J
NEXT I
FOR I = 1 TO 8
LET E = E + B(I) * 2 ^ (8 - I)
NEXT I
LET E=E-127
FOR I = 9 TO 31
LET S = S + B(I) * 2 ^ (8 - I)
NEXT I
LET X=2^E*(S+1)
IF B(0)=1 THEN LET X=-X
LET CVS=X
END FUNCTION
EXTERNAL FUNCTION MKS$(X)
!'IEEE754 32bit float to str
OPTION CHARACTER BYTE
OPTION BASE 0
DIM B(32)
IF X < 0 THEN LET B(0)=1
IF X<>0 THEN
IF ABS(X) < 1 THEN
DO WHILE 2^(N+1) > ABS(X)
LET N=N-1
LOOP
LET N=N+1
ELSE
DO WHILE 2^(N+1) < ABS(X)
LET N=N+1
LOOP
END IF
LET NN=N
LET N=N+127
FOR I=1 TO 8
IF AND(N,2^(8-I))<>0 THEN LET B(I)=1
NEXT I
LET T=(ABS(X)-2^NN)/2^NN
FOR I=9 TO 31
LET T=T*2
IF T >= 1 THEN
LET B(I)=1
LET T=T-INT(T)
END IF
NEXT I
END IF
LET AA$=CHR$(B(0)*128+B(1)*64+B(2)*32+B(3)*16+B(4)*8+B(5)*4+B(6)*2+B(7))
LET BB$=CHR$(B(8)*128+B(9)*64+B(10)*32+B(11)*16+B(12)*8+B(13)*4+B(14)*2+B(15))
LET CC$=CHR$(B(16)*128+B(17)*64+B(18)*32+B(19)*16+B(20)*8+B(21)*4+B(22)*2+B(23))
LET DD$=CHR$(B(24)*128+B(25)*64+B(26)*32+B(27)*16+B(28)*8+B(29)*4+B(30)*2+B(31))
LET MKS$=DD$ & CC$ & BB$ & AA$
END FUNCTION
EXTERNAL FUNCTION FLOAT2STR$(X,L,M) !'可変精度浮動小数変換
!'符号(1 bit) 指数部(L bit) 仮数部(M bit)
OPTION CHARACTER BYTE
OPTION BASE 0
IF MOD(L+M+1,8)<>0 THEN EXIT FUNCTION
DIM B(1+L+M)
IF X < 0 THEN LET B(0)=1
IF X<>0 THEN
IF ABS(X) < 1 THEN
DO WHILE 2^(N+1) > ABS(X)
LET N=N-1
LOOP
LET N=N+1
ELSE
DO WHILE 2^(N+1) < ABS(X)
LET N=N+1
LOOP
END IF
FOR I=1 TO L
IF AND(N+2^(L-1)-1,2^(L-I))<>0 THEN LET B(I)=1
NEXT I
LET T=(ABS(X)-2^N)/2^N
FOR I=1+L TO 1+L+M
LET T=T*2
IF T >= 1 THEN
LET B(I)=1
LET T=T-INT(T)
END IF
NEXT I
END IF
FOR J=0 TO (1+L+M)/8-1
LET AA$=CHR$(B(8*J)*128+B(8*J+1)*64+B(8*J+2)*32+B(8*J+3)*16+B(8*J+4)*8+B(8*J+5)*4+B(8*J+6)*2+B(8*J+7)) & AA$
NEXT J
LET FLOAT2STR$=AA$
END FUNCTION
EXTERNAL FUNCTION STR2FLOAT(A$,N,M)
!'符号(1 bit) 指数部(N bit) 仮数部(M bit)
OPTION CHARACTER BYTE
OPTION BASE 0
IF MOD(N+M+1,8)<>0 THEN EXIT FUNCTION
DIM B(1+N+M)
LET K=0
FOR I=INT((1+N+M)/8) TO 1 STEP -1
LET D$=MID$(A$, I, 1)
FOR J=0 TO 7
IF AND(ORD(D$),2^(7-J))<>0 THEN LET B(K)=1
LET K=K+1
NEXT J
NEXT I
FOR I=1 TO N
LET E=E+B(I)*2^(N-I)
NEXT I
LET E=E-(2^(N-1)-1)
FOR I=1+N TO 1+N+M
LET S=S+B(I)*2^(N-I)
NEXT I
LET X=2^E*(1+S)
IF B(0)=1 THEN LET X=-X
LET STR2FLOAT=X
END FUNCTION
|
|