golang获取java uuid的mostSigBits和leastSigBits

EasyNetCN · · 512 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

一直在解决golang直接使用spring cloud stream的问题,计划实现无缝对接,首先解决的是head中生成java uuid的问题,因为spring cloud stream的head是基于java序列化的,所以golang也要实现同样的序列化。

下面的代码是获取uuid中的mostSigBits和leastSigBits,用于java格式的uuid序列化。

package main

import (
    "fmt"
    "strconv"
    "strings"

    "github.com/google/uuid"
)

const (
    DATE_TIME_PATTERN = ""
    STREAM_MAGIC      = 0xaced
    STREAM_VERSION    = 5
    TC_STRING         = 0x74
    TC_OBJECT         = 0x73
    TC_CLASSDESC      = 0x72
    SC_SERIALIZABLE   = 0x02
    TC_ENDBLOCKDATA   = 0x78
    TC_NULL           = 0x70
)

func main() {
    uidStr := "8bb489cc-7810-4514-82dd-bce071748a83"

    mostSigBits, leastSigBits, err := UUIDSStringSigBits(uidStr)

    fmt.Println(mostSigBits, leastSigBits, err)

    uid, _ := uuid.Parse(uidStr)

    fmt.Println(UUIDSigBits(uid))

}

func UUIDSStringSigBits(uuid string) (int64, int64, error) {
    mostSigBits := int64(0)
    leastSigBits := int64(0)

    dash1 := strings.Index(uuid, "-")
    dash2 := dash1 + 1 + strings.Index(uuid[dash1+1:], "-")
    dash3 := dash2 + 1 + strings.Index(uuid[dash2+1:], "-")
    dash4 := dash3 + 1 + strings.Index(uuid[dash3+1:], "-")

    if result, err := strconv.ParseInt(uuid[0:dash1], 16, 64); err != nil {
        return 0, 0, err
    } else {
        mostSigBits = result & 0xffffffff
    }

    mostSigBits <<= 16

    if result, err := strconv.ParseInt(uuid[dash1+1:dash2], 16, 64); err != nil {
        return 0, 0, err
    } else {
        mostSigBits |= result & 0xffff
    }

    mostSigBits <<= 16

    if result, err := strconv.ParseInt(uuid[dash2+1:dash3], 16, 64); err != nil {
        return 0, 0, err
    } else {
        mostSigBits |= result & 0xffff
    }

    if result, err := strconv.ParseInt(uuid[dash3+1:dash4], 16, 64); err != nil {
        return 0, 0, err
    } else {
        leastSigBits = result & 0xffff
    }

    leastSigBits <<= 48

    if result, err := strconv.ParseInt(uuid[dash4+1:], 16, 64); err != nil {
        return 0, 0, err
    } else {
        leastSigBits |= result & 0xffffffffffff
    }

    return mostSigBits, leastSigBits, nil
}

func UUIDSigBits(uuid uuid.UUID) (int64, int64) {
    msb := int64(0)
    lsb := int64(0)

    for i := 0; i < 8; i++ {
        msb = (msb << 8) | int64((uuid[i] & 0xff))
    }

    for i := 8; i < 16; i++ {
        lsb = (lsb << 8) | int64(uuid[i]&0xff)
    }

    return msb, lsb

}

有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:EasyNetCN

查看原文:golang获取java uuid的mostSigBits和leastSigBits

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

512 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传