Skip to content

Commit

Permalink
created f32 to int8 and int16, related to issue #27
Browse files Browse the repository at this point in the history
  • Loading branch information
Zeda committed Apr 5, 2021
1 parent 9dcc526 commit 648cb7c
Show file tree
Hide file tree
Showing 2 changed files with 143 additions and 0 deletions.
79 changes: 79 additions & 0 deletions conversion/f32toi16.z80
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
#ifndef included_f32toi16
#define included_f32toi16

f32toi16:
;Inputs: HL points to an f32 float
;Outputs: HL is the signed 16-bit integer part of the input (rounded down)
;NaN ==> 0
;+inf ==> 32767
;-inf ==> -32768
push de
push bc
push af
ld e,(hl)
inc hl
ld d,(hl)
inc hl
ld a,(hl)
rlca
scf
rra
ld c,a
inc hl
ld a,(hl)
adc a,a

; carry flag is sign, CDE is the significand, A is the exponent
push af ; carry flag is a sign

call f32toi16_get_int

pop af ; get the carry flag
ld a,h
jr nc,f32toi16_return
; -HL-1
ld a,l
cpl
ld l,a
ld a,h
cpl
ld h,a
f32toi16_return:
pop af
pop bc
pop de
ret

f32toi16_get_int:
ld hl,32767
cp 142
ret nc
sub h ;
ld hl,0
ret c
ld b,a

; if the exponent is 128, return 0 if NaN, else inf
jp p,f32toi16_extract
ld a,l
or e
or d
ret nz
ld hl,32767
ret
f32toi16_extract:
inc b
ld l,d
ld h,c
xor a
ld e,a

add hl,hl
rl e
rla
djnz $-4

ld h,a
ld l,e
ret
#endif
64 changes: 64 additions & 0 deletions conversion/f32toi8.z80
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
#ifndef included_f32toi8
#define included_f32toi8

f32toi8:
;Inputs: HL points to an f32 float
;Outputs: A is the signed 8-bit integer part of the input (rounded down)
;NaN ==> 0
;+inf ==> 127
;-inf ==> -128
push hl
push de
push bc
ld e,(hl)
inc hl
ld d,(hl)
inc hl
ld a,(hl)
rlca
scf
rra
ld c,a
inc hl
ld a,(hl)
adc a,a

; carry flag is sign, CDE is the significand, A is the exponent
push af ; carry flag is a sign

call f32toi8_get_int

pop af ; get the carry flag
; if carry is set, return -H-1, else return H
sbc a,a
xor h
f32toi8_return:
pop bc
pop de
pop hl
ret

f32toi8_get_int:
ld h,127
cp 134
ret nc
sub h
ld h,0
ret c
ld l,c ; upper 8 bits of the significand
ld b,a

; if the exponent is 128, return inf
jp p,f32toi8_extract
ld a,l
or e
or d
ret nz
ld h,127
ret
f32toi8_extract:
inc b
add hl,hl
djnz $-1
ret
#endif

1 comment on commit 648cb7c

@Zeda
Copy link
Owner

@Zeda Zeda commented on 648cb7c Apr 5, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

correction: addresses #29

Please sign in to comment.