美文网首页
[go语言算法]bytes和int互转

[go语言算法]bytes和int互转

作者: Ucan先生 | 来源:发表于2019-08-14 23:41 被阅读0次

    bytes与32位int互转
    package main

    import (
    "fmt"
    "reflect"
    )

    func intToBytes(num int) []byte {
    bytes := []byte{0, 0, 0, 0}
    bytes[3] = (byte)((num >> 24) & 0xFF)
    bytes[2] = (byte)((num >> 16) & 0xFF)
    bytes[1] = (byte)((num >> 8) & 0xFF)
    bytes[0] = (byte)(num & 0xFF)
    return bytes
    }

    func bytesToInt(bytes []byte) (num int) {
    num = (num | int(bytes[0])) + (num | int(bytes[1])<<8) + (num | int(bytes[2])<<16) + (num | int(bytes[3])<<24)
    return
    }

    func main() {
    a := intToBytes(123123)
    fmt.Println(a)
    fmt.Println(int(bytesToInt(a)))
    }

    相关文章

      网友评论

          本文标题:[go语言算法]bytes和int互转

          本文链接:https://www.haomeiwen.com/subject/tpiojctx.html