This question already has an answer here:
I follow the article about building blockchain in go: https://jeiwan.cc/posts/building-blockchain-in-go-part-2/ When I study the part 2, I can't run the code in the prepareDate
function. It always throw up a error:
underfined: IntToHex.
This is my code:
func (pow *ProofOfWork) prepareData(nonce int) []byte {
data := bytes.Join(
[][]byte{
pow.block.PrevBlockHash,
pow.block.Data,
IntToHex(pow.block.Timestamp),
IntToHex(int64(targetBits)),
IntToHex(int64(nonce)),
},
[]byte{},
)
return data
}
</div>
the article you linked contains an url to the full source code
in the file utils.go is the IntToHex
function used
package main
import (
"bytes"
"encoding/binary"
"log"
)
// IntToHex converts an int64 to a byte array
func IntToHex(num int64) []byte {
buff := new(bytes.Buffer)
err := binary.Write(buff, binary.BigEndian, num)
if err != nil {
log.Panic(err)
}
return buff.Bytes()
}
Looks like the author of that article left that function out of his/her example, or implied the reader to write their own. Representing an integer as its base-16 format is quite easily and can be done using the standard library's strconv package. Here's an example below of one I believe would fit your program:
func IntToHex(n int64) []byte {
return []byte(strconv.FormatInt(n, 16))
}
Just use
s := fmt.Sprintf("%0x", 745658)
fmt.Println(s)
// Output: b60ba