gpt4 book ai didi

python-3.x - 将Go的PutUint16转换为Python

转载 作者:行者123 更新时间:2023-12-01 22:34:51 24 4
gpt4 key购买 nike

我想获得与以下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语言编写编译器》一书,可以找到 here

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

最佳答案

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

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

关于python-3.x - 将Go的PutUint16转换为Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60019167/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com