?login_element?

Subversion Repositories NedoOS

Rev

Blame | Last modification | View Log | Download | RSS feed

  1. #ifndef included_f32toi16
  2. #define included_f32toi16
  3.  
  4. f32toi16:
  5. ;Inputs: HL points to an f32 float
  6. ;Outputs: HL is the signed 16-bit integer part of the input (rounded down)
  7. ;Special cases:
  8. ;   NaN              ==> 0
  9. ;   greater than 127 ==> 32767
  10. ;   less than -128   ==> -32768
  11.   push de
  12.   push bc
  13.   push af
  14.  
  15.   ld c,(hl)
  16.   inc hl
  17.   ld e,(hl)
  18.   inc hl
  19.   ld a,(hl)
  20.   rlca
  21.   scf
  22.   rra
  23.   ld d,a
  24.   inc hl
  25.   ld a,(hl)
  26.   adc a,a
  27. ; carry flag is sign, DEC is the significand, A is the exponent
  28.   call f32toi16_get_int
  29. f32toi16_return:
  30.   pop af
  31.   pop bc
  32.   pop de
  33.   ret
  34.  
  35. f32toi16_infnan:
  36.   ; if the exponent is 128, return 0 if NaN, else inf
  37.   ld a,d
  38.   add a,a
  39.   or e
  40.   or c
  41.   ret nz
  42. f32toi16_inf:
  43.   ld hl,32767
  44.   rr b
  45.   ret nc
  46.   inc hl
  47.   ret
  48.  
  49. f32toi16_zero_ish:
  50.   rr b
  51.   ret nc
  52.   ld a,d
  53.   add a,a
  54.   or e
  55.   or c
  56.   ret z
  57.   dec hl
  58.   ret
  59.  
  60. f32toi16_get_int:
  61.   rl b    ; save the sign
  62.   ld hl,0
  63.   inc a
  64.   jr z,f32toi16_infnan
  65.   jp p,f32toi16_zero_ish
  66.   sub 128
  67.   cp 15
  68.   jr nc,f32toi16_inf
  69.   ex de,hl  ; significand is in HLC now, but we don't need to track C
  70.   ;DE is 0
  71.   cp 7
  72.   jr c,$+7
  73.   ;shift up by 8
  74.   sub 8
  75.   ld e,h
  76.   ld h,l
  77.   ld l,d    ; 0
  78.  
  79.   ld d,b    ; save sign
  80.   ld b,a
  81.   xor a
  82.   ;AE.HLC
  83.   inc b
  84.   jr z,$+8
  85.   add hl,hl
  86.   rl e
  87.   rla
  88.   djnz $-4
  89.  
  90.   ld b,d    ; save sign again
  91.   ld d,a
  92.   ex de,hl
  93.   ; HL is the result, DEC has any fractional bits
  94.  
  95.   rrc b   ; if carry is reset, then we are done
  96.   ret nc
  97.   ; otherwise the number is negative, so if the fractional part is non-zero,
  98.   ; need to round down
  99.  
  100.   xor a
  101.   sub l
  102.   ld l,a
  103.   sbc a,a
  104.   sub h
  105.   ld h,a
  106.  
  107.   ld a,c
  108.   or d
  109.   or e
  110.   ret z
  111.   dec hl
  112.   ret
  113. #endif
  114.