开发者

Python : Convert from C-Char to Int

开发者 https://www.devze.com 2023-01-01 11:39 出处:网络
I have a string read in from a binary file that is unpacked using struct.unpack as a string of length n.

I have a string read in from a binary file that is unpacked using struct.unpack as a string of length n.

Each byte in the string is a single integer (1-byte) representing 0-255. So for each character in the string I want to convert it to an integer.

I can't figure out 开发者_开发问答how to do this. Using ord doesn't seem to be on the right track...


>>> import struct
>>> a = struct.pack("ccc", "a", "b", "c")
>>> a
b'abc'
>>> b = struct.unpack("ccc", a)
>>> b
(b'a', b'b', b'c')
>>> ord(b[0])
97
>>> c = struct.pack("BBB", 1, 2, 3)
>>> c
b'\x01\x02\x03'
>>> d = struct.unpack("BBB", c)
>>> d
(1, 2, 3)

Works for me.

0

精彩评论

暂无评论...
验证码 换一张
取 消