code wiki / (root) / nx_fp32_q14_test.nx

nx_fp32_q14_test.nx source

↩ module page · 60 lines · 2571 B

1// nx_fp32_q14_test.nx -- IEEE 754 binary32 -> Q14 conversion against 2// known bit patterns. Pure math test, no I/O. 3// 4// Closed-form expected values (computed by hand from the IEEE 754 5// spec; Q14 unit = 1/16384 so q14 = value * 16384): 6// 7// bits value expected q14 8// 0x00000000 0.0 0 9// 0x3F800000 1.0 16384 10// 0x40000000 2.0 32768 11// 0x3F000000 0.5 8192 12// 0xBF800000 -1.0 -16384 13// 0x44800000 1024.0 16777216 (= 2^24) 14// 0x42C80000 100.0 1638400 15// 0x7F800000 +Inf NX_FP32_Q14_INVALID 16// 0x7FC00000 NaN NX_FP32_Q14_INVALID 17// 0x00000001 tiny subnormal 0 18// 19// expect_exit: 0 20// license_tier: ORIGINAL 21 22import "nx_syscalls.nx" 23import "nx_fp32_q14.nx" 24 25func main() -> i64 { 26 if nx_fp32_bits_to_q14(0x00000000) != 0 { return 10 } 27 if nx_fp32_bits_to_q14(0x3F800000) != 16384 { return 11 } 28 if nx_fp32_bits_to_q14(0x40000000) != 32768 { return 12 } 29 if nx_fp32_bits_to_q14(0x3F000000) != 8192 { return 13 } 30 if nx_fp32_bits_to_q14(0xBF800000) != -16384 { return 14 } 31 if nx_fp32_bits_to_q14(0x44800000) != 16777216 { return 15 } 32 if nx_fp32_bits_to_q14(0x42C80000) != 1638400 { return 16 } 33 34 if nx_fp32_bits_to_q14(0x7F800000) != NX_FP32_Q14_INVALID { return 20 } 35 if nx_fp32_bits_to_q14(0x7FC00000) != NX_FP32_Q14_INVALID { return 21 } 36 if nx_fp32_bits_to_q14(0x00000001) != 0 { return 22 } 37 38 // Bulk variant: 3 floats (1.0, 2.0, 0.5) -> [16384, 32768, 8192] 39 let buf: *u8 = sys_mmap(12) 40 // 1.0 = 0x3F800000 = bytes 00 00 80 3F (little endian) 41 buf[0] = 0x00; buf[1] = 0x00; buf[2] = 0x80; buf[3] = 0x3F 42 // 2.0 = 0x40000000 = bytes 00 00 00 40 43 buf[4] = 0x00; buf[5] = 0x00; buf[6] = 0x00; buf[7] = 0x40 44 // 0.5 = 0x3F000000 = bytes 00 00 00 3F 45 buf[8] = 0x00; buf[9] = 0x00; buf[10] = 0x00; buf[11] = 0x3F 46 let out: *i64 = (sys_mmap(24)) as *i64 47 let n: i64 = nx_fp32_bytes_to_q14(buf, 0, 3, out) 48 if n != 3 { return 30 } 49 if out[0] != 16384 { return 31 } 50 if out[1] != 32768 { return 32 } 51 if out[2] != 8192 { return 33 } 52 53 // Bulk variant stops on Inf -- inject 0x7F800000 at slot 1. 54 buf[4] = 0x00; buf[5] = 0x00; buf[6] = 0x80; buf[7] = 0x7F 55 let n_bad: i64 = nx_fp32_bytes_to_q14(buf, 0, 3, out) 56 if n_bad != 1 { return 40 } // stopped at slot 1 57 if out[0] != 16384 { return 41 } // slot 0 valid 58 59 return 0 60}