4

Using Geth I am reading from a smart contract and a list of addresses is retrieved when outputting to the terminal. These addresses are in byte array format:

fmt.printLn("address", address)
output = address  [16 22 32 12 22 0 0 0 0 0 16 0 0 0 0 0 0 0 0 3]

when I try to convert back to hex I keep coming against the following:

cannot use address (type common.Address) as type string in argument to bytes.NewBufferString

So far, I have tried various different ways to make the conversion but with no luck: string(address[:] etc etc...

Anyone have any clues?

2
  • Have you tried string(address.GetBytes())? May 24, 2018 at 14:48
  • its throws address.GetBytes undefined (type common.Address has no field or method GetBytes)
    – Kravitz
    May 24, 2018 at 14:52

2 Answers 2

5

to convert from binary to hex, and back, use the package encoding/hex

Hex ==> string:

str := hex.EncodeToString(**your slice of bytes**)

Hex <== string:

b, err := hex.DecodeString(**your string**)
5
  • address.Sum undefined (type common.Address has no field or method Sum)
    – Kravitz
    May 24, 2018 at 15:03
  • oh sorry about that, the input is your slice of bytes
    – Mheni
    May 24, 2018 at 15:10
  • Sweet! that did the trick
    – Kravitz
    May 24, 2018 at 15:27
  • that's if you want lower case address, if you want a checksumed just do str:=address_var.Hex()
    – Nulik
    Jun 7, 2018 at 23:40
  • hexutil.Decode also works. Nov 1, 2018 at 21:21
2

go-ethereum also provides a hexutil package.

package main

import (
    "fmt"

    "github.com/ethereum/go-ethereum/common/hexutil"
)

func main() {
    addrBytes := []byte{20, 123, 142, 185, 127, 210, 71, 208, 108, 64, 6, 210, 105, 201, 12, 25, 8, 251, 93, 84}
    fmt.Println(hexutil.Encode(addrBytes)) // 0x147B8eb97fD247D06C4006D269c90C1908Fb5D54

    addrHex, _ := hexutil.Decode("0x147B8eb97fD247D06C4006D269c90C1908Fb5D54")
    fmt.Println(addrHex) // [20 123 142 185 127 210 71 208 108 64 6 210 105 201 12 25 8 251 93 84]
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.