登录
首页 >  Golang >  Go问答

将 Go 的 PutUint16 转换为 Python

来源:stackoverflow

时间:2024-04-23 15:21:35 459浏览 收藏

golang学习网今天将给大家带来《将 Go 的 PutUint16 转换为 Python》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

问题内容

我想获得与下面给出的 python 中的 go 代码等效的内容:

func make(op opcode, operands ...int) []byte {
    def, ok := definitions[op]
    if !ok {
        return []byte{}
    }

    instructionlen := 1
    for _, w := range def.operandwidths {
        instructionlen += w
    }

    instruction := make([]byte, instructionlen)
    instruction[0] = byte(op)

    offset := 1
    for i, o := range operands {
        width := def.operandwidths[i]
        switch width {
        case 2:
            binary.bigendian.putuint16(instruction[offset:], uint16(o))
        case 1:
            instruction[offset] = byte(o)
        }
        offset += width
    }

    return instruction
}

func readoperands(def *definition, ins instructions) ([]int, int) {
    operands := make([]int, len(def.operandwidths))
    offset := 0

    for i, width := range def.operandwidths {
        switch width {
        case 2:
            operands[i] = int(readuint16(ins[offset:]))
        case 1:
            operands[i] = int(readuint8(ins[offset:]))
        }

        offset += width
    }

    return operands, offset
}

上面的 op 是以下任意一个:

type Opcode byte

const (
    OpConstant Opcode = iota

    OpAdd

    OpPop

    OpSub
    OpMul
    OpDiv
)

上面的代码来自《writing a compiler in go》一书,可以在这里找到

我不太确定字节转换和打包到底发生了什么,但为了更好地理解它,我用 python 编写了整个过程。有人可以帮我用 python 翻译这两个函数吗?


解决方案


可以使用整数的to_bytes方法。 o.to_bytes(2, byteorder='big') 将提供与 PutUint16 相同的效果。同样,int.from_bytes 也可用于读取。还有 struct.pack 以格式字符串的方式处理类似的事情。

与 Go 代码中那样构建缓冲区并写入偏移量不同,简单地使用 + 附加到以空开头的 bytes 更有意义。

终于介绍完啦!小伙伴们,这篇关于《将 Go 的 PutUint16 转换为 Python》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>