~sbinet/star-tex

ref: bb815b96d680a95dffcd37f85c943e1957eb47ed star-tex/font/fixed/int12_20.go -rw-r--r-- 1.5 KiB
bb815b96Sebastien Binet font/fixed: add convenience method to convert Int12_20 to Int26_6 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
54
55
56
57
58
59
60
61
62
// 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"

	"golang.org/x/image/math/fixed"
)

// 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
}

// Float64 converts the 12.20 fixed-point number to a floating point one.
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)).
}

// ToInt26_6 converts the 12.20 fixed-point number to a 26.6 one.
func (x Int12_20) ToInt26_6() fixed.Int26_6 {
	f := x.Float64()
	return fixed.Int26_6(f * (1 << 6))
}