doudi2005 2019-04-16 02:35
浏览 1805

去如何实现python binascii.unhexlify方法?

In my company there is a system written in python and I want to reimplement it using golang.

Question

Python binascii.unhexlify seems complex, and I don't know hot to implement it in go.

  • 写回答

1条回答 默认 最新

  • dougu1990 2019-04-16 03:06
    关注

    binascii.unhexlify method is simple enough. It's just converting from hex to binary. Every two hex digits is an 8-bit byte (256 possible values). here is my code

    func unhexlify(str string) []byte {
        res := make([]byte, 0)
        for i := 0; i < len(str); i+=2 {
            x, _ := strconv.ParseInt(str[i:i+2], 16, 32)
            res = append(res, byte(x))
        }
        return res
    }
    

    I should use the library

    func ExampleDecodeString() {
        const s = "48656c6c6f20476f7068657221"
        decoded, err := hex.DecodeString(s)
        if err != nil {
            log.Fatal(err)
        }
    
        fmt.Printf("%s
    ", decoded)
    
        // Output:
        // Hello Gopher!
    }
    
    评论

报告相同问题?