1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
use super::{P8E0, Q8E0};
use crate::WithSign;
use core::convert::From;
use core::f64;

crate::impl_convert!(P8E0, Q8E0);

fn check_extra_two_bits_p8(
    mut float: f64,
    mut temp: f64,
    bits_n_plus_one: &mut bool,
    bits_more: &mut bool,
) {
    temp /= 2.;
    if temp <= float {
        *bits_n_plus_one = true;
        float -= temp;
    }
    if float > 0. {
        *bits_more = true;
    }
}

fn convert_fraction_p8(
    mut float: f64,
    mut frac_length: u8,
    bits_n_plus_one: &mut bool,
    bits_more: &mut bool,
) -> u8 {
    let mut frac = 0_u8;

    if float == 0. {
        return 0;
    } else if float == f64::INFINITY {
        return 0x80;
    }

    float -= 1.; //remove hidden bit
    if frac_length == 0 {
        check_extra_two_bits_p8(float, 1., bits_n_plus_one, bits_more);
    } else {
        let mut temp = 1_f64;
        loop {
            temp /= 2.;
            if temp <= float {
                float -= temp;
                frac_length -= 1;
                frac = (frac << 1) + 1; //shift in one
                if float == 0. {
                    //put in the rest of the bits
                    frac <<= frac_length as u8;
                    break;
                }

                if frac_length == 0 {
                    check_extra_two_bits_p8(float, temp, bits_n_plus_one, bits_more);

                    break;
                }
            } else {
                frac <<= 1; //shift in a zero
                frac_length -= 1;
                if frac_length == 0 {
                    check_extra_two_bits_p8(float, temp, bits_n_plus_one, bits_more);
                    break;
                }
            }
        }
    }
    frac
}

impl From<f32> for P8E0 {
    fn from(float: f32) -> Self {
        Self::from(float as f64)
    }
}

impl From<f64> for P8E0 {
    fn from(mut float: f64) -> Self {
        let mut reg: u8;
        let mut bit_n_plus_one = false;
        let mut bits_more = false;

        if float == 0. {
            return Self::ZERO;
        } else if !float.is_finite() {
            return Self::INFINITY;
        } else if float >= 64. {
            //maxpos
            return Self::MAX;
        } else if float <= -64. {
            // -maxpos
            return Self::MIN;
        }

        let sign = float < 0.;
        // sign: 1 bit, frac: 8 bits, mantisa: 23 bits
        //sign = a.parts.sign;
        //frac = a.parts.fraction;
        //exp = a.parts.exponent;

        let u_z: u8 = if float == 0. {
            0
        } else if float == 1. {
            0x40
        } else if float == -1. {
            0xC0
        } else if (float <= 0.015_625) && !sign {
            //minpos
            0x1
        } else if (float >= -0.015_625) && sign {
            //-minpos
            0xFF
        } else if (float > 1.) || (float < -1.) {
            if sign {
                //Make negative numbers positive for easier computation
                float = -float;
            }
            reg = 1; //because k = m-1; so need to add back 1
                     // minpos
            if float <= 0.015_625 {
                1
            } else {
                //regime
                while float >= 2. {
                    float *= 0.5;
                    reg += 1;
                }

                //rounding off regime bits
                if reg > 6 {
                    0x7F
                } else {
                    let frac_length = 6 - reg;
                    let frac = convert_fraction_p8(
                        float,
                        frac_length,
                        &mut bit_n_plus_one,
                        &mut bits_more,
                    );
                    let regime = 0x7F - (0x7F >> reg);
                    let mut u_z = P8E0::pack_to_ui(regime, frac);
                    if bit_n_plus_one {
                        u_z += (u_z & 1) | (bits_more as u8);
                    }
                    u_z
                }
                .with_sign(sign)
            }
        } else if (float < 1.) || (float > -1.) {
            if sign {
                //Make negative numbers positive for easier computation
                float = -float;
            }
            reg = 0;

            //regime
            //printf("here we go\n");
            while float < 1. {
                float *= 2.;
                reg += 1;
            }
            //rounding off regime bits
            if reg > 6 {
                0x1
            } else {
                let frac_length = 6 - reg;
                let frac =
                    convert_fraction_p8(float, frac_length, &mut bit_n_plus_one, &mut bits_more);
                let regime = 0x40 >> reg;
                let mut u_z = P8E0::pack_to_ui(regime, frac);
                if bit_n_plus_one {
                    u_z += (u_z & 1) | (bits_more as u8);
                }
                u_z
            }
            .with_sign(sign)
        } else {
            //NaR - for NaN, INF and all other combinations
            0x80
        };
        Self::from_bits(u_z)
    }
}

#[cfg(feature = "float_convert")]
impl From<P8E0> for f32 {
    #[inline]
    fn from(a: P8E0) -> Self {
        f64::from(a) as f32
    }
}

#[cfg(feature = "float_convert")]
impl From<P8E0> for f64 {
    #[inline]
    fn from(a: P8E0) -> Self {
        let mut u_z = a.to_bits();

        if u_z == 0 {
            return 0.;
        } else if u_z == 0x7F {
            //maxpos
            return 64.;
        } else if u_z == 0x81 {
            //-maxpos
            return -64.;
        } else if u_z == 0x80 {
            //NaR
            return f64::NAN;
        }

        let sign = P8E0::sign_ui(u_z);
        if sign {
            u_z = u_z.wrapping_neg()
        };
        let reg_s = P8E0::sign_reg_ui(u_z);

        let mut shift = 2_u8;
        let mut k = 0_i8;
        let mut tmp = u_z<<2 /* & 0xFF*/;
        let reg = if reg_s {
            while (tmp & 0x_80) != 0 {
                k += 1;
                shift += 1;
                tmp <<= 1 /* & 0xFF*/;
            }
            k + 1
        } else {
            k = -1;
            while (tmp >> 7) == 0 {
                k -= 1;
                shift += 1;
                tmp <<= 1 /* & 0xFF*/;
            }
            tmp &= 0x7F;
            -k
        } as u8;
        let frac = (tmp & 0x7F) >> shift;

        let fraction_max = libm::pow(2., (6 - reg) as f64);
        let d8 = (libm::pow(2., k as f64) * (1. + ((frac as f64) / fraction_max))) as f64;

        if sign {
            -d8
        } else {
            d8
        }
    }
}

impl From<P8E0> for i32 {
    #[inline]
    fn from(p_a: P8E0) -> Self {
        let mut i_z: i32;

        let mut ui_a = p_a.to_bits();

        //NaR
        if ui_a == 0x80 {
            return -0x8000_0000;
        }

        let sign = ui_a > 0x80; // sign is True if p_a > NaR.
        if sign {
            ui_a = ui_a.wrapping_neg(); // A is now |A|.
        }
        if ui_a <= 0x20 {
            // 0 <= |p_a| <= 1/2 rounds to zero.
            return 0;
        } else if ui_a < 0x50 {
            // 1/2 < x < 3/2 rounds to 1.
            i_z = 1;
        } else {
            let (scale, bits) = P8E0::calculate_scale(ui_a);

            i_z = (((bits as u32) | 0x40) << 24) as i32; // Left-justify fraction in 32-bit result (one left bit padding)
            let mut mask = 0x4000_0000_i32 >> scale; // Point to the last bit of the integer part.

            let bit_last = (i_z & mask) != 0; // Extract the bit, without shifting it.
            mask >>= 1;
            let mut tmp = i_z & mask;
            let bit_n_plus_one = tmp != 0; // "True" if nonzero.
            i_z ^= tmp; // Erase the bit, if it was set.
            tmp = i_z & (mask - 1); // tmp has any remaining bits. // This is bits_more
            i_z ^= tmp; // Erase those bits, if any were set.

            if bit_n_plus_one {
                // logic for round to nearest, tie to even
                if (bit_last as i32 | tmp) != 0 {
                    i_z += mask << 1;
                }
            }

            i_z = ((i_z as u32) >> (30 - scale)) as i32; // Right-justify the integer.
        }

        if sign {
            i_z = -i_z; // Apply the sign of the input.
        }
        i_z
    }
}

impl From<P8E0> for i64 {
    #[inline]
    fn from(p_a: P8E0) -> Self {
        let mut i_z: i64;

        let mut ui_a = p_a.to_bits();

        //NaR
        if ui_a == 0x80 {
            return -0x8000_0000_0000_0000;
        }

        let sign = (ui_a & 0x_80) != 0;
        if sign {
            ui_a = ui_a.wrapping_neg();
        }

        if ui_a <= 0x20 {
            // 0 <= |p_a| <= 1/2 rounds to zero.
            return 0;
        } else if ui_a < 0x50 {
            // 1/2 < x < 3/2 rounds to 1.
            i_z = 1;
        } else {
            let (scale, bits) = P8E0::calculate_scale(ui_a);

            i_z = (((bits as u64) | 0x40) << 55) as i64; // Left-justify fraction in 32-bit result (one left bit padding)

            let mut mask = 0x2000_0000_0000_0000_i64 >> scale; // Point to the last bit of the integer part.

            let bit_last = (i_z & mask) != 0; // Extract the bit, without shifting it.
            mask >>= 1;
            let mut tmp = i_z & mask;
            let bit_n_plus_one = tmp != 0; // "True" if nonzero.
            i_z ^= tmp; // Erase the bit, if it was set.
            tmp = i_z & (mask - 1); // tmp has any remaining bits. // This is bits_more
            i_z ^= tmp; // Erase those bits, if any were set.

            if bit_n_plus_one {
                // logic for round to nearest, tie to even
                if (bit_last as i64 | tmp) != 0 {
                    i_z += mask << 1;
                }
            }
            i_z = ((i_z as u64) >> (61 - scale)) as i64; // Right-justify the integer.
        }

        if sign {
            i_z = -i_z; // Apply the sign of the input.
        }
        i_z
    }
}

impl From<P8E0> for u32 {
    #[inline]
    fn from(p_a: P8E0) -> Self {
        let mut i_z: u32;

        let ui_a = p_a.to_bits();

        //NaR
        if ui_a == 0x80 {
            return 0x8000_0000;
        } else if ui_a > 0x80 {
            return 0; //negative
        }
        if ui_a <= 0x20 {
            // 0 <= |p_a| <= 1/2 rounds to zero.
            return 0;
        } else if ui_a < 0x50 {
            // 1/2 < x < 3/2 rounds to 1.
            i_z = 1;
        } else {
            let (scale, bits) = P8E0::calculate_scale(ui_a);

            i_z = ((bits as u32) | 0x40) << 24; // Left-justify fraction in 32-bit result (one left bit padding)

            let mut mask = 0x4000_0000_u32 >> scale; // Point to the last bit of the integer part.

            let bit_last = (i_z & mask) != 0; // Extract the bit, without shifting it.
            mask >>= 1;
            let mut tmp = i_z & mask;
            let bit_n_plus_one = tmp != 0; // "True" if nonzero.
            i_z ^= tmp; // Erase the bit, if it was set.
            tmp = i_z & (mask - 1); // tmp has any remaining bits. // This is bits_more
            i_z ^= tmp; // Erase those bits, if any were set.

            if bit_n_plus_one {
                // logic for round to nearest, tie to even
                if (bit_last as u32 | tmp) != 0 {
                    i_z += mask << 1;
                }
            }
            i_z >>= 30 - scale; // Right-justify the integer.
        }

        i_z
    }
}

impl From<P8E0> for u64 {
    #[inline]
    fn from(p_a: P8E0) -> Self {
        let mut i_z: u64;

        let ui_a = p_a.to_bits();
        //NaR
        if ui_a == 0x80 {
            return 0x8000_0000_0000_0000;
        } else if ui_a > 0x80 {
            return 0; //negative
        }
        if ui_a <= 0x20 {
            // 0 <= |p_a| <= 1/2 rounds to zero.
            return 0;
        } else if ui_a < 0x50 {
            // 1/2 < x < 3/2 rounds to 1.
            i_z = 1;
        } else {
            let (scale, bits) = P8E0::calculate_scale(ui_a);

            i_z = ((bits as u64) | 0x40) << 55; // Left-justify fraction in 32-bit result (one left bit padding)

            let mut mask = 0x2000_0000_0000_0000_u64 >> scale; // Point to the last bit of the integer part.

            let bit_last = (i_z & mask) != 0; // Extract the bit, without shifting it.
            mask >>= 1;
            let mut tmp = i_z & mask;
            let bit_n_plus_one = tmp != 0; // "True" if nonzero.
            i_z ^= tmp; // Erase the bit, if it was set.
            tmp = i_z & (mask - 1); // tmp has any remaining bits. // This is bits_more
            i_z ^= tmp; // Erase those bits, if any were set.

            if bit_n_plus_one {
                // logic for round to nearest, tie to even
                if (bit_last as u64 | tmp) != 0 {
                    i_z += mask << 1;
                }
            }
            i_z >>= 61 - scale; // Right-justify the integer.
        }

        i_z
    }
}

impl From<u32> for P8E0 {
    #[inline]
    fn from(a: u32) -> Self {
        Self::from_bits(convert_u32_to_p8bits(a))
    }
}

impl From<i32> for P8E0 {
    #[inline]
    fn from(mut a: i32) -> Self {
        let sign = a.is_negative();
        if sign {
            a = -a;
        }
        Self::from_bits(convert_u32_to_p8bits(a as u32).with_sign(sign))
    }
}

impl From<u64> for P8E0 {
    #[inline]
    fn from(a: u64) -> Self {
        Self::from_bits(convert_u64_to_p8bits(a))
    }
}

impl From<i64> for P8E0 {
    #[inline]
    fn from(mut a: i64) -> Self {
        let sign = a.is_negative();
        if sign {
            a = -a;
        }
        Self::from_bits(convert_u64_to_p8bits(a as u64).with_sign(sign))
    }
}

fn convert_u32_to_p8bits(a: u32) -> u8 {
    if a == 0x8000_0000 {
        0x80
    } else if a > 48 {
        0x7F
    } else if a < 2 {
        (a << 6) as u8
    } else {
        let mut log2 = 6_i8; //length of bit
        let mut mask = 0x40_u32;
        let mut frac_a = a;
        while (frac_a & mask) == 0 {
            log2 -= 1;
            frac_a <<= 1;
        }

        let k = log2;

        frac_a ^= mask;

        let mut ui_a: u8 = (0x7F ^ (0x3F >> k)) | (frac_a >> (k + 1)) as u8;

        mask = 0x1 << k; //bit_n_plus_one
        if ((mask & frac_a) != 0) && ((((mask - 1) & frac_a) | ((mask << 1) & frac_a)) != 0) {
            ui_a += 1;
        }
        ui_a
    }
}

fn convert_u64_to_p8bits(a: u64) -> u8 {
    if a == 0x8000_0000_0000_0000 {
        0x80
    } else if a > 48 {
        0x7F
    } else if a < 2 {
        (a << 6) as u8
    } else {
        let mut log2 = 6_i8; //length of bit
        let mut mask = 0x40_u64;
        let mut frac_a = a;
        while (frac_a & mask) == 0 {
            log2 -= 1;
            frac_a <<= 1;
        }

        let k = log2;

        frac_a ^= mask;

        let mut ui_a: u8 = (0x7F ^ (0x3F >> k)) | (frac_a >> (k + 1)) as u8;

        mask = 0x1 << k; //bit_n_plus_one
        if ((mask & frac_a) != 0) && ((((mask - 1) & frac_a) | ((mask << 1) & frac_a)) != 0) {
            ui_a += 1;
        }
        ui_a
    }
}

impl From<Q8E0> for P8E0 {
    #[inline]
    fn from(q_a: Q8E0) -> Self {
        if q_a.is_zero() {
            return Self::ZERO;
        } else if q_a.is_nar() {
            return Self::NAR;
        }

        let mut u_z = q_a.to_bits();

        let sign = (u_z & 0x8000_0000) != 0;

        if sign {
            u_z = u_z.wrapping_neg();
        }

        let mut no_lz = 0_i8;
        let mut tmp = u_z;
        while (tmp >> 31) == 0 {
            no_lz += 1;
            tmp <<= 1;
        }
        let mut frac32_a = tmp;

        //default dot is between bit 19 and 20, extreme left bit is bit 0. Last right bit is bit 31.
        //Scale =  k
        let k_a = 19 - no_lz;

        let (regime, reg_sa, reg_a) = Self::calculate_regime(k_a);

        let u_a = if reg_a > 6 {
            //max or min pos. exp and frac does not matter.
            if reg_sa {
                0x7F
            } else {
                0x1
            }
        } else {
            //remove hidden bit
            frac32_a &= 0x7FFF_FFFF;
            let shift = reg_a + 25; // 1 sign bit and 1 r terminating bit , 16+7+2
            let frac_a = (frac32_a >> shift) as u8;

            let bit_n_plus_one = ((frac32_a >> (shift - 1)) & 0x1) != 0;

            let mut u_a = Self::pack_to_ui(regime, frac_a);

            if bit_n_plus_one {
                let bits_more = (frac32_a << (33 - shift)) != 0;
                u_a += (u_a & 1) | (bits_more as u8);
            }
            u_a
        };

        Self::from_bits(u_a.with_sign(sign))
    }
}

#[test]
fn convert_p8_f64() {
    for n in -0x_80_i8..0x_7f {
        let p = P8E0::new(n);
        let f = f64::from(p);
        assert_eq!(p, P8E0::from(f));
    }
}