![](/img/trans.png)
[英]How to convert string of ints of type unsigned char to an int in python
[英]How to convert unsigned char to int with python
我在 C 中有以下代码
#include <stdio.h>
int main ()
{
unsigned char mask = 0xAB;
for (int i = 0; i < 20; i++)
{
printf ("%d - %x\n", mask, mask);
mask += 9;
}
return 0;
}
C语言输出
171 - ab
180 - b4
189 - bd
198 - c6
207 - cf
216 - d8
225 - e1
234 - ea
243 - f3
252 - fc
5 - 5
14 - e
23 - 17
32 - 20
41 - 29
50 - 32
59 - 3b
68 - 44
77 - 4d
86 - 56
现在在 Python 中:
mask = 0xab
for i in range(20):
print("{0:d} - {0:x}".format(mask,mask))
mask = (mask + 9) % 0xFF
输出 Python:
171 - ab
180 - b4
189 - bd
198 - c6
207 - cf
216 - d8
225 - e1
234 - ea
243 - f3
252 - fc
6 - 6
15 - f
24 - 18
33 - 21
42 - 2a
51 - 33
60 - 3c
69 - 45
78 - 4e
87 - 57
如您所见,正确的输出是 C 代码的输出,但是在 python 中,我尝试了各种使用 pack()、to_bytes() 的方法,但找不到正确的结果,我该如何纠正呢?
提前致谢
你应该用 256(Hex: 0x100
) 取模。 这是因为 C unsigned char
数据类型的范围是0
到255
。
>>> mask = 0xab >>> for i in range(20): ... print("{0:d} - {0:x}".format(mask,mask)) ... mask = (mask + 9) % 0x100 ...
这将产生与您的 C 代码相同的输出!。
171 - ab
180 - b4
189 - bd
198 - c6
207 - cf
216 - d8
225 - e1
234 - ea
243 - f3
252 - fc
5 - 5
14 - e
23 - 17
32 - 20
41 - 29
50 - 32
59 - 3b
68 - 44
77 - 4d
86 - 56
非常感谢,之前我看不到,你为我解决了一个问题,因为这是构建一个函数来加密或解密协议帧的基础。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.