~sbinet/star-tex

ref: 035c3b7ca661b1baeb227791426869600519c051 star-tex/font/fixed/int12_20.go -rw-r--r-- 1.3 KiB
035c3b7cSebastien Binet all: retract v0.1.x and v0.3.0 modules 8 months ago
                                                                                
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
// Copyright ©2021 The star-tex Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package fixed

import (
	"fmt"
	"strconv"
)

// Int12_20 is a signed 12.20 fixed-point number.
//
// The integer part ranges from -2048 to 2047, inclusive. The
// fractional part has 20 bits of precision.
type Int12_20 uint32

// I12_20 returns the integer value i as an Int12_20.
//
// For example, passing the integer value 2 yields Int12_20(2097152).
func I12_20(v int) Int12_20 {
	return Int12_20(v << 20)
}

// ParseInt12_20 converts the string s to a signed 12.20 fixed-point number.
func ParseInt12_20(s string) (Int12_20, error) {
	f, err := strconv.ParseFloat(s, 32)
	if err != nil {
		return 0, err
	}
	return Int12_20(f * (1 << 20)), nil
}

func (x Int12_20) Float64() float64 {
	v := int32(x)
	return float64(v) / (1 << 20)
}

// String returns a human-readable representation of a 12.20 fixed-point number.
func (x Int12_20) String() string {
	const (
		shift = 12
		mask  = 1<<shift - 1
	)
	if x >= 0 {
		return fmt.Sprintf("%d:%02d", int32(x>>shift), int32(x&mask))
	}
	x = -x
	if x >= 0 {
		return fmt.Sprintf("-%d:%02d", int32(x>>shift), int32(x&mask))
	}
	return "-2048:00" // The minimum value is -(1<<(12-1)).
}