当前位置: 首页>>代码示例>>Golang>>正文


Golang Int.String方法代码示例

本文整理汇总了Golang中math/big.Int.String方法的典型用法代码示例。如果您正苦于以下问题:Golang Int.String方法的具体用法?Golang Int.String怎么用?Golang Int.String使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在math/big.Int的用法示例。


在下文中一共展示了Int.String方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: CreateID

func CreateID(d *schema.ResourceData, meta interface{}) error {

	byteLength := d.Get("byte_length").(int)
	bytes := make([]byte, byteLength)

	n, err := rand.Reader.Read(bytes)
	if n != byteLength {
		return fmt.Errorf("generated insufficient random bytes")
	}
	if err != nil {
		return fmt.Errorf("error generating random bytes: %s", err)
	}

	b64Str := base64.RawURLEncoding.EncodeToString(bytes)
	hexStr := hex.EncodeToString(bytes)

	int := big.Int{}
	int.SetBytes(bytes)
	decStr := int.String()

	d.SetId(b64Str)
	d.Set("b64", b64Str)
	d.Set("hex", hexStr)
	d.Set("dec", decStr)

	return nil
}
开发者ID:RezaDKhan,项目名称:terraform,代码行数:27,代码来源:resource_id.go

示例2: Join

/*
	The Join function
	The first fuction to be executed
	Alaows it gives the hash and id and request the finger table for the boost node
*/
func Join(test bool) { //

	//generate id
	me.nodeId = Index(generateNodeId(), BITS)
	nodeIdInt := me.nodeId
	me.storage = map[string]string{}

	//prepare finger table
	if test { //firstnode in the ring
		me.offset = 0
		for i, _ := range me.FingerTable {
			//compute the ith node
			two := big.NewInt(2)
			dist := big.Int{}
			dist.Exp(two, big.NewInt(int64(i)), nil)
			var ithNode big.Int
			ithNode.Add(&dist, &nodeIdInt)
			x := ringSize(BITS)
			ithNode.Mod(&ithNode, &x)
			//fill the fingr table row
			me.FingerTable[i][0] = ithNode.String()
			me.FingerTable[i][1] = me.nodeId.String()
			me.FingerTable[i][2] = me.address //this node address
		}
	} else { //not first node in the ring
		//initialize offset
		GetOffsetClient(me.target)
		updateFingerTable(nodeIdInt, me.target) //target server required
		go infornMySuccessor()
		go AutoUpdate() // initialize auto update
	}

}
开发者ID:hamzamac,项目名称:chord,代码行数:38,代码来源:dht_node.go

示例3: StartUP

func StartUP() {
	nodeStore := peerNode.NewNodeStore("", "")
	go read(nodeStore.OutFindNode, nodeStore.InNodes)
	running := true
	reader := bufio.NewReader(os.Stdin)

	for running {
		data, _, _ := reader.ReadLine()
		command := string(data)
		switch command {
		case "find":
			findNode, _ := new(big.Int).SetString("27", 10)
			// peerNode.Print(findNode)
			node := nodeStore.Get(findNode.String())
			// peerNode.Print(node.NodeId)
			fmt.Println(node)
		case "quit":
			running = false
		case "see":
			nodes := nodeStore.GetAllNodes()
			fmt.Println(nodes)
		case "self":
			fmt.Println("自己节点的id:")
			rootId := nodeStore.GetRootId()
			// peerNode.Print(rootId)
			fmt.Println(rootId)
		case "cap":
		case "odp":
		case "cdp":
		case "dump":
		}
	}
}
开发者ID:cokeboL,项目名称:mandela,代码行数:33,代码来源:simple.go

示例4: floatString

func (i BigInt) floatString(verb byte, prec int) string {
	switch verb {
	case 'f', 'F':
		str := fmt.Sprintf("%d", i.Int)
		if prec > 0 {
			str += "." + zeros(prec)
		}
		return str
	case 'e', 'E':
		// The exponent will alway be >= 0.
		sign := ""
		var x big.Int
		x.Set(i.Int)
		if x.Sign() < 0 {
			sign = "-"
			x.Neg(&x)
		}
		return eFormat(verb, prec, sign, x.String(), eExponent(&x))
	case 'g', 'G':
		// Exponent is always positive so it's easy.
		var x big.Int
		x.Set(i.Int)
		if eExponent(&x) >= prec {
			// Use e format.
			verb -= 2 // g becomes e.
			return trimEZeros(verb, i.floatString(verb, prec-1))
		}
		// Use f format, but this is just an integer.
		return fmt.Sprintf("%d", i.Int)
	default:
		Errorf("can't handle verb %c for big int", verb)
	}
	return ""
}
开发者ID:jmptrader,项目名称:ivy,代码行数:34,代码来源:bigint.go

示例5: handleBalance

// Handles the load balancing event of a topio.
func (o *Overlay) handleBalance(msg *proto.Message, topicId *big.Int, prevHop *big.Int) (bool, error) {
	sid := topicId.String()

	// Fetch the topic or report not found
	o.lock.RLock()
	top, ok := o.topics[sid]
	topName := o.names[sid]
	o.lock.RUnlock()
	if !ok {
		// No error, but not handled either
		return false, nil
	}
	// Fetch the recipient and either forward or deliver
	node, err := top.Balance(prevHop)
	if err != nil {
		return true, err
	}
	// If it's a remote node, forward
	if node.Cmp(o.pastry.Self()) != 0 {
		o.fwdBalance(node, msg)
		return true, nil
	}
	// Remove all carrier headers and decrypt
	head := msg.Head.Meta.(*header)
	msg.Head.Meta = head.Meta
	if err := msg.Decrypt(); err != nil {
		return true, err
	}
	// Deliver to the application on the specific topic
	o.app.HandleBalance(head.Sender, topName, msg)
	return true, nil
}
开发者ID:ibmendoza,项目名称:iris-0.3.2,代码行数:33,代码来源:events.go

示例6: handleSubscribe

// Handles the subscription event to a topic.
func (o *Overlay) handleSubscribe(nodeId, topicId *big.Int) error {
	// Generate the textual topic id
	sid := topicId.String()

	// Make sure the requested topic exists, then subscribe
	o.lock.Lock()
	top, ok := o.topics[sid]
	if !ok {
		top = topic.New(topicId, o.pastry.Self())
		o.topics[sid] = top
	}
	o.lock.Unlock()

	// Subscribe node to the topic
	if err := top.Subscribe(nodeId); err != nil {
		return err
	}
	// If a remote node, start monitoring is and respond with an empty report (fast parent discovery)
	if nodeId.Cmp(o.pastry.Self()) != 0 {
		if err := o.monitor(topicId, nodeId); err != nil {
			return err
		}
		rep := &report{
			Tops: []*big.Int{topicId},
			Caps: []int{1},
		}
		o.sendReport(nodeId, rep)
	}
	return nil
}
开发者ID:ibmendoza,项目名称:iris-0.3.2,代码行数:31,代码来源:events.go

示例7: handleUnsubscribe

// Handles the unsubscription event from a topic.
func (o *Overlay) handleUnsubscribe(nodeId, topicId *big.Int) error {
	o.lock.Lock()
	defer o.lock.Unlock()

	// Fetch the topic and ensure it exists
	sid := topicId.String()
	top, ok := o.topics[sid]
	if !ok {
		return errors.New("non-existent topic")
	}
	// Unsubscribe node from the topic and unmonitor if remote
	if err := top.Unsubscribe(nodeId); err != nil {
		return err
	}
	if nodeId.Cmp(o.pastry.Self()) != 0 {
		if err := o.unmonitor(topicId, nodeId); err != nil {
			return err
		}
	}
	// If topic became empty, send unsubscribe to parent and delete
	if top.Empty() {
		if parent := top.Parent(); parent != nil {
			if err := o.unmonitor(topicId, parent); err != nil {
				return err
			}
			top.Reown(nil)
			go o.sendUnsubscribe(parent, top.Self())
		}
		delete(o.topics, sid)
	}
	return nil
}
开发者ID:ibmendoza,项目名称:iris-0.3.2,代码行数:33,代码来源:events.go

示例8: TestStringMarshal

// Test marshaling back and forth between string and int
// Pretty much a sanity check for further tests
func TestStringMarshal(t *testing.T) {
	for _, tc := range idTestCases {
		i := new(big.Int)
		i.SetString(tc.base10, 10)
		assert.Equal(t, tc.base10, i.String())
	}
}
开发者ID:leibowitz,项目名称:kala,代码行数:9,代码来源:id_test.go

示例9: compute

func compute(count *big.Int) (keys [ResultsPerPage]Key, length int) {
	var padded [32]byte

	var i int
	for i = 0; i < ResultsPerPage; i++ {
		// Increment our counter
		count.Add(count, one)

		// Check to make sure we're not out of range
		if count.Cmp(total) > 0 {
			break
		}

		// Copy count value's bytes to padded slice
		copy(padded[32-len(count.Bytes()):], count.Bytes())

		// Get private and public keys
		privKey, public := btcec.PrivKeyFromBytes(btcec.S256(), padded[:])

		// Get compressed and uncompressed addresses for public key
		caddr, _ := btcutil.NewAddressPubKey(public.SerializeCompressed(), &btcnet.MainNetParams)
		uaddr, _ := btcutil.NewAddressPubKey(public.SerializeUncompressed(), &btcnet.MainNetParams)

		// Encode addresses
		wif, _ := btcutil.NewWIF(privKey, &btcnet.MainNetParams, false)
		keys[i].private = wif.String()
		keys[i].number = count.String()
		keys[i].compressed = caddr.EncodeAddress()
		keys[i].uncompressed = uaddr.EncodeAddress()
	}
	return keys, i
}
开发者ID:dedcode,项目名称:directory.io,代码行数:32,代码来源:directory.go

示例10: newPasswd

func newPasswd() {
	ClearScreen()
	wr("Make new password\n")

t:
	key := ins("Name of password: ")
	if in := validate(key); in != "" {
		wr("You used an invalid character in your name: ", in)
		goto t
	}
	strlen := ins("Password length: ")
	ig := in("Characters to not include: ")

	ilen, err := strconv.Atoi(strlen)
	if err != nil {
		pause("That wasn't a number")
		return
	}

	passes[key] = NewPass(ilen, ig)

	if Debug {
		fmt.Println("Debug dump:\n\t", passes)
	}

	a, b := big.NewInt(int64(Mod-len(ig))), big.NewInt(int64(ilen))
	var z big.Int
	z.Exp(a, b, nil)
	fmt.Printf("Made new password; Approx chance of guessing = 1/%s\n\n", z.String())
	pause("note that changes have not been saved.")
}
开发者ID:Carrotman42,项目名称:otp-pwman,代码行数:31,代码来源:ui.go

示例11: main

func main() {

	var count int // initialize count at zero
	distinct_powers := make(map[string]bool)

	for a := 2; a < 101; a++ {
		for b := 2; b < 101; b++ {

			// have to use big.Int because the exponents exceed 20 digits fast
			var ex big.Int
			ex.Exp(big.NewInt(int64(a)), big.NewInt(int64(b)), nil)
			// have to convert back to string because
			// map won't accept big.Int as a key
			term := ex.String()

			if !distinct_powers[term] {
				distinct_powers[term] = true
				count++
			}
		}
	}

	fmt.Println(count)

}
开发者ID:cpolitano,项目名称:project-euler-go,代码行数:25,代码来源:main.go

示例12: InsertNode

//插入一个节点
//@node 待插入的节点
func (this *Bucket) InsertNode(node Node) {
	selfInt, _ := new(big.Int).SetString(this.GetRootId(), 10)
	insertInt, _ := new(big.Int).SetString(node.NodeId, 10)
	fmt.Println(node)
	fmt.Println(insertInt.String())
	this.insertLoop(selfInt, insertInt, node)
}
开发者ID:cokeboL,项目名称:mandela,代码行数:9,代码来源:kademlia.go

示例13: main

func main() {
	zaroStr := "0000000000000000000000000000000000000000000000000000000000000000"
	maxNumberStr := "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
	idStr := "9d1406a76433f43ab752f468e0ca58baf73c9adddfc505a617c5756ea310e44f"
	idInt, _ := new(big.Int).SetString(idStr, 16)
	fmt.Println(len(idStr), len(zaroStr), len(maxNumberStr))

	maxNumberInt, ok := new(big.Int).SetString(maxNumberStr, 16)
	if !ok {
		fmt.Println("失败")
		return
	}

	fmt.Println(maxNumberInt.String(), len(maxNumberInt.String()))
	number_2 := big.NewInt(2)
	halfNumberInt := new(big.Int).Quo(maxNumberInt, number_2)

	fmt.Println(hex.EncodeToString(halfNumberInt.Bytes()))

	halfAndHalfNumberInt := new(big.Int).Quo(halfNumberInt, number_2)
	fmt.Println(hex.EncodeToString(halfAndHalfNumberInt.Bytes()))

	fmt.Println(new(big.Int).Sub(maxNumberInt, idInt))

	// Print(maxNumberInt)

}
开发者ID:cokeboL,项目名称:mandela,代码行数:27,代码来源:test.go

示例14: SendToConn

func SendToConn(data []byte, conn *net.TCPConn, path *big.Int) {
	// making variable for combining send data
	var (
		err           tree_lib.TreeError
		path_len_data = make([]byte, 4)
		msg_len_data  = make([]byte, 4)
		path_data     = path.Bytes()
		path_len      = uint32(len(path_data))
		buf           = bytes.Buffer{}
	)

	err.From = tree_lib.FROM_SEND_TO_CONN

	binary.LittleEndian.PutUint32(path_len_data, path_len)
	binary.LittleEndian.PutUint32(msg_len_data, path_len+uint32(len(data))+uint32(4))

	buf.Write(msg_len_data)
	buf.Write(path_len_data)
	buf.Write(path_data)
	buf.Write(data)

	if conn != nil {
		_, err.Err = conn.Write(buf.Bytes())
		if !err.IsNull() {
			tree_log.Error(err.From, fmt.Sprintf("Error sending data to path [%s]", path.String()), err.Error())
		}
	}

	buf.Reset()
}
开发者ID:treescale,项目名称:treescale,代码行数:30,代码来源:network.go

示例15: filter

// Checks whether a bootstrap-located peer fits into the local routing table or
// will be just discarded anyway.
func (o *Overlay) filter(id *big.Int) bool {
	o.lock.RLock()
	defer o.lock.RUnlock()

	// Discard already connected nodes
	if _, ok := o.livePeers[id.String()]; ok {
		return true
	}

	table := o.routes

	// Check for empty slot in leaf set
	for i, leaf := range table.leaves {
		if leaf.Cmp(o.nodeId) == 0 {
			if delta(id, leaf).Sign() >= 0 && i < config.PastryLeaves/2 {
				return false
			}
			if delta(leaf, id).Sign() >= 0 && len(table.leaves)-i < config.PastryLeaves/2 {
				return false
			}
			break
		}
	}
	// Check for better leaf set
	if delta(table.leaves[0], id).Sign() >= 0 && delta(id, table.leaves[len(table.leaves)-1]).Sign() >= 0 {
		return false
	}
	// Check place in routing table
	pre, col := prefix(o.nodeId, id)
	if prev := table.routes[pre][col]; prev == nil {
		return false
	}
	// Nowhere to insert, bin it
	return true
}
开发者ID:ibmendoza,项目名称:iris-0.3.2,代码行数:37,代码来源:handshake.go


注:本文中的math/big.Int.String方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。