3

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?

  • Have you tried string(address.GetBytes())? – Alex Papageorgiou May 24 '18 at 14:48
  • its throws address.GetBytes undefined (type common.Address has no field or method GetBytes) – Kravitz May 24 '18 at 14:52
3

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**)
  • address.Sum undefined (type common.Address has no field or method Sum) – Kravitz May 24 '18 at 15:03
  • oh sorry about that, the input is your slice of bytes – Mheni May 24 '18 at 15:10
  • Sweet! that did the trick – Kravitz May 24 '18 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 '18 at 23:40
  • hexutil.Decode also works. – Paul Razvan Berg Nov 1 '18 at 21:21
1

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, privacy policy and cookie policy

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