【go】strconv.Iota源码

7 篇文章 0 订阅

Iota方法用来将int类型转换为string类型

func Itoa(i int) string {
	return FormatInt(int64(i), 10)
}

内部只是调用FormatInt,指定base为10

const nSmalls = 100
func FormatInt(i int64, base int) string {
	if fastSmalls && 0 <= i && i < nSmalls && base == 10 {
		return small(int(i))
	}
	_, s := formatBits(nil, uint64(i), base, i < 0, false)
	return s
}
small

如果是小于100的正整数,则进入samll方法

const smallsString = "00010203040506070809" +
	"10111213141516171819" +
	"20212223242526272829" +
	"30313233343536373839" +
	"40414243444546474849" +
	"50515253545556575859" +
	"60616263646566676869" +
	"70717273747576777879" +
	"80818283848586878889" +
	"90919293949596979899"
const digits = "0123456789abcdefghijklmnopqrstuvwxyz"
func small(i int) string {
	if i < 10 {
		return digits[i : i+1]
	}
	return smallsString[i*2 : i*2+2]
}

small方法很简单,通过直接截取预先定义的字符串获取对应的值。

formatBits

先看方法签名

//dst和append_用来标识是否将结果追加到指定byte数组中,并使用d []byte返回。否则使用s string返回。
func formatBits(dst []byte, u uint64, base int, neg, append_ bool) (d []byte, s string)

只看base=10的逻辑

func formatBits(dst []byte, u uint64, base int, neg, append_ bool) (d []byte, s string) {
	if base < 2 || base > len(digits) {
		panic("strconv: illegal AppendInt/FormatInt base")
	}
	// 2 <= base && base <= len(digits)

	// 声明一个64+1位的字节数组,+1用来表示正负
	var a [64 + 1]byte
	i := len(a)

	if neg {
		u = -u
	}

	// 使用uint可以兼容32位机器
	if base == 10 {
		// 省略 32位的处理
		if host32bit {}

		// u guaranteed to fit into a uint
		us := uint(u)
		// 大于100时,循环取余添加进a
		for us >= 100 {
			is := us % 100 * 2
			us /= 100
			i -= 2
			a[i+1] = smallsString[is+1]
			a[i+0] = smallsString[is+0]
		}

		// 循环结束,处理剩余的值
		is := us * 2
		i--
		a[i] = smallsString[is+1]
		if us >= 10 {
			i--
			a[i] = smallsString[is]
		}
	}
	// 处理符号
	if neg {
		i--
		a[i] = '-'
	}

	// 处理append方式
	if append_ {
		d = append(dst, a[i:]...)
		return
	}
	s = string(a[i:])
	return
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值