douhan1860 2019-02-09 20:22
浏览 226
已采纳

连接[] byte和哈希

I have something like

unixtime := time.Now().Unix()

unixtimeStr := string(unixtime)

soup := make([]byte, len(data) + len(nonce) + len(unixtimeStr) + len(previousHash))

copy(soup[:], data)
copy(soup[len(data):], nonce)
copy(soup[len(data) + len(nonce):], []byte(unixtimeStr))
copy(soup[len(data) + len(nonce) + len(unixtimeStr):], previousHash)

hasher := sha1.New()
hasher.Write(soup)
var hash []byte = hasher.Sum(nil)

data, nonce, previousHash are of type []byte.

I find it so dirty and unreadable!

I'd like a more object oriented coding style like

soup := data.concat(nonce).concat([]byte(unixtimeStr)).concat(previousHash)

or at least something like

soup := concat(data, nonce, ...)

How would you write this snippet?

  • 写回答

2条回答 默认 最新

  • dongyin5516 2019-02-09 20:33
    关注

    For example,

    var data, nonce, previousHash []byte
    
    unixtime := strconv.FormatInt(time.Now().Unix(), 10)
    hasher := sha1.New()
    hasher.Write(data)
    hasher.Write(nonce)
    hasher.Write([]byte(unixtime))
    hasher.Write(previousHash)
    hash := hasher.Sum(nil)
    

    Or,

    var data, nonce, previousHash []byte
    
    unixtime := strconv.FormatInt(time.Now().Unix(), 10)
    soup := make([]byte, 0, len(data)+len(nonce)+len(unixtime)+len(previousHash))
    soup = append(soup, data...)
    soup = append(soup, nonce...)
    soup = append(soup, unixtime...)
    soup = append(soup, previousHash...)
    hasher := sha1.New()
    hasher.Write(soup)
    hash := hasher.Sum(nil)
    

    Note:

    unixtime := time.Now().Unix()
    unixtimeStr := string(unixtime)
    

    is nonsensical. It's always the Unicode replacement character. For example,

    package main
    
    import (
        "fmt"
        "time"
        "unicode"
    )
    
    func main() {
        unixtime := time.Now().Unix()
        unixtimeStr := string(unixtime)
        fmt.Println(unixtimeStr == string(unicode.ReplacementChar))
    }
    

    Output:

    true
    

    To convert an integer to a string, use the strconv package. For example,

    package main
    
    import (
        "fmt"
        "strconv"
        "time"
    )
    
    func main() {
        unixtimeStr := strconv.FormatInt(time.Now().Unix(), 10)
        fmt.Println(unixtimeStr)
    }
    

    Output:

    1257894000
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改