当前位置: > > > > 将 Go 的 PutUint16 转换为 Python
将 Go 的 PutUint16 转换为 Python
来源:stackoverflow
2024-04-23 15:21:35
0浏览
收藏
米云今天将给大家带来《将 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 翻译这两个函数吗?
解决方案
可以使用整数的方法。 o.to_bytes(2, byteorder='big') 将提供与 PutUint16 相同的效果。同样, 也可用于读取。还有 以格式字符串的方式处理类似的事情。
与 Go 代码中那样构建缓冲区并写入偏移量不同,简单地使用 + 附加到以空开头的 bytes 更有意义。
终于介绍完啦!小伙伴们,这篇关于《将 Go 的 PutUint16 转换为 Python》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~米云公众号也会发布Golang相关知识,快来关注吧!
