Go语言-big.Int

Go 语言 big.Int

Go 语言 big.Int
参考URL: https://blog.csdn.net/wzygis/article/details/82867793

math/big 作为 Go 语言提供的进行大数操作的官方库。

big.Int 用于表示 大整数。

应用场景:大整数位运算

在密码学、加密算法或者需要处理大数字的领域中,使用大整数进行位操作是非常常见的。

实战demo:来自cosmos的 bip39.go

  ...
 
	// Break entropy up into sentenceLength chunks of 11 bits
	// For each word AND mask the rightmost 11 bits and find the word at that index
	// Then bitshift entropy 11 bits right and repeat
	// Add to the last empty slot so we can work with LSBs instead of MSB

	// Entropy as an int so we can bitmask without worrying about bytes slices
	entropyInt := new(big.Int).SetBytes(entropy)

	// Slice to hold words in
	words := make([]string, sentenceLength)

	// Throw away big int for AND masking
	word := big.NewInt(0)

	for i := sentenceLength - 1; i >= 0; i-- {
		// Get 11 right most bits and bitshift 11 to the right for next time
		word.And(entropyInt, Last11BitsMask)
		entropyInt.Div(entropyInt, RightShift11BitsDivider)

		// Get the bytes representing the 11 bits as a 2 byte slice
		wordBytes := padByteSlice(word.Bytes(), 2)

		// Convert bytes to an index and add that word to the list
		words[i] = WordList[binary.BigEndian.Uint16(wordBytes)]
	}

	return strings.Join(words, " "), nil
}

代码解析:

entropyInt := new(big.Int).SetBytes(entropy) 这行代码的作用是将字节切片 entropy 转换为大整数。

将这些字节数据转换为大整数可以方便进行位操作、数学运算等操作,同时也能保持精度和范围。因此,将字节转换为大整数是一种常见的做法

  • 将熵(entropy)分成长度为 sentenceLength 的 11 位比特。
  • 对于每个单词,将最右边的 11 位进行按位与(AND)运算,并找到该索引位置的单词。
  • 然后将熵向右移动 11 位,重复上述操作。

使用举例: go sdk中crypto/ecdsa 椭圆曲线生成私钥相关结构中就有使用

举例:
比如 go sdk中crypto/ecdsa 椭圆曲线生成私钥相关结构中就有使用到,demo如下:
key, err := ecdsa.GenerateKey(secp256k1.S256(), seed)

// PublicKey represents an ECDSA public key.
type PublicKey struct {
	elliptic.Curve
	X, Y *big.Int
}

// PrivateKey represents an ECDSA private key.
type PrivateKey struct {
	PublicKey
	D *big.Int
}

相关推荐

  1. Go语言GC

    2024-06-05 23:30:02       56 阅读
  2. Go教程-Go语言简介

    2024-06-05 23:30:02       61 阅读
  3. go语言的基础语法

    2024-06-05 23:30:02       25 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-05 23:30:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-05 23:30:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-06-05 23:30:02       87 阅读
  4. Python语言-面向对象

    2024-06-05 23:30:02       96 阅读

热门阅读

  1. 亚信安慧AntDB:全新的数据库体验

    2024-06-05 23:30:02       34 阅读
  2. rust calcmine读取excel

    2024-06-05 23:30:02       29 阅读
  3. c++模板进阶——特化

    2024-06-05 23:30:02       26 阅读
  4. 【WP|8】深入解析WordPress钩子函数

    2024-06-05 23:30:02       21 阅读
  5. 2024年6月-7月

    2024-06-05 23:30:02       31 阅读
  6. tomcat 配置ssl

    2024-06-05 23:30:02       27 阅读
  7. Android应用保活攻略

    2024-06-05 23:30:02       32 阅读