[英]Python three integers to hex string
I'm using python to control a mouse, for that I need to convert 3 integers to a hex value like b'\\x00\\x64\\x64'
我正在使用python控制鼠标,因此我需要将3个整数转换为十六进制值,例如
b'\\x00\\x64\\x64'
return b'\x00' + hex(x) + hex(y)
But my IDE doesn't like this syntax, am I missing anything? 但是我的IDE不喜欢这种语法,我丢失了什么吗?
The simplest is probably to use the struct
module: 最简单的方法可能是使用
struct
模块:
import struct
def f(x, y):
return struct.pack('bbb', 0, x, y)
Another way to do it without struct
: 没有
struct
另一种方法:
def byte_to_bytestr(x):
return x.to_bytes(1, byteorder='big')
def f(x, y):
return b''.join(map(byte_to_bytestr, [0, x, y]))
x = 100
y = 100
print(bytes("\x00\{}\{}".format(hex(x), hex(y)), 'utf-8'))
That should do the trick 这应该够了吧
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.