如何从uuid获得2个长数字?

时间:2016-02-01 20:27:33

标签: go uuid

我正在使用此库生成v4 uuid:

https://github.com/satori/go.uuid

从生成的uuid中获取2个长整数的最有效方法是什么?

2 个答案:

答案 0 :(得分:3)

您可以使用Bytes()函数获取字节,然后使用encoding/binary转换为long。正如@icza所提到的,您也可以直接对UUID对象进行切片,因此您甚至不需要致电Bytes()

package main

import "fmt"
import "encoding/binary"
import "github.com/satori/go.uuid"

func main() {
    u1 := uuid.NewV4()
    fmt.Printf("UUIDv4: %s\n", u1)

    l1 := binary.BigEndian.Uint64(u1[:8])
    l2 := binary.BigEndian.Uint64(u1[8:])

    fmt.Printf("%x %x\n", l1, l2)
    fmt.Printf("%v %v\n", l1, l2)
}

答案 1 :(得分:1)

例如,

package main

import (
    "encoding/binary"
    "fmt"

    "github.com/satori/go.uuid"
)

func main() {
    u := uuid.NewV4()
    fmt.Printf("%s\n", u)
    u1 := binary.BigEndian.Uint64(u[0:8])
    u2 := binary.BigEndian.Uint64(u[8:16])
    fmt.Printf("%x %x\n", u1, u2)
}

输出:

eb33dcfa-e439-4ff9-b366-bcd397e0852f
eb33dcfae4394ff9 b366bcd397e0852f