v / vlib / math
Raw file | 59 loc (51 sloc) | 1.61 KB | Latest commit hash a8ace2c41
1module math
2
3// f32_bits returns the IEEE 754 binary representation of f,
4// with the sign bit of f and the result in the same bit position.
5// f32_bits(f32_from_bits(x)) == x.
6pub fn f32_bits(f f32) u32 {
7 p := u32(0)
8 #let buffer = new ArrayBuffer(4)
9 #let floatArr = new Float32Array(buffer)
10 #floatArr[0] = f.val
11 #let uintArr = new Uint32Array(buffer)
12 #p.val = uintArr[0]
13
14 return p
15}
16
17// f32_from_bits returns the floating-point number corresponding
18// to the IEEE 754 binary representation b, with the sign bit of b
19// and the result in the same bit position.
20// f32_from_bits(f32_bits(x)) == x.
21pub fn f32_from_bits(b u32) f32 {
22 p := f32(0.0)
23 #let buffer = new ArrayBuffer(4)
24 #let floatArr = new Float32Array(buffer)
25 #let uintArr = new Uint32Array(buffer)
26 #uintArr[0] = Number(b.val)
27 #p.val = floatArr[0]
28
29 return p
30}
31
32// f64_bits returns the IEEE 754 binary representation of f,
33// with the sign bit of f and the result in the same bit position,
34// and f64_bits(f64_from_bits(x)) == x.
35pub fn f64_bits(f f64) u64 {
36 p := u64(0)
37 #let buffer = new ArrayBuffer(8)
38 #let floatArr = new Float64Array(buffer)
39 #floatArr[0] = f.val
40 #let uintArr = new BigUint64Array(buffer)
41 #p.val = uintArr[0]
42
43 return p
44}
45
46// f64_from_bits returns the floating-point number corresponding
47// to the IEEE 754 binary representation b, with the sign bit of b
48// and the result in the same bit position.
49// f64_from_bits(f64_bits(x)) == x.
50pub fn f64_from_bits(b u64) f64 {
51 p := 0.0
52 #let buffer = new ArrayBuffer(8)
53 #let floatArr = new Float64Array(buffer)
54 #let uintArr = new BigUint64Array(buffer)
55 #uintArr[0] = b.val
56 #p.val = floatArr[0]
57
58 return p
59}