将 Go 的 PutUint16 转换为 Python

我想在 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

)

上面的代码来自《用 Go 编写编译器》一书,可以在这里找到


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


婷婷同学_
浏览 259回答 1
1回答

慕容森

您可以使用整数的to_bytes方法。o.to_bytes(2, byteorder='big')将产生与 相同的效果PutUint16。同样int.from_bytes可用于读取。还有struct.pack以格式字符串的方式处理类似的事情。与在 Go 代码中所做的那样构建缓冲区并写入偏移量不同,简单地使用+附加到bytes以空开头的 a 会更有意义。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go