I have an external app that appends the length of the packet at the start of the data. Something like the following code:
我有一个外部应用程序,在数据的开头附加数据包的长度。类似下面的代码:
x = "ABCDE"
x_len = len(x)
y = "GHIJK"
y_len = len(y)
test_string = chr(x_len) + x + chr(y_len) + y
#TODO:perform base64 encoding
In the client side of the code I need to be able to extract x_len and y_len and read x and y accrodingly.
在代码的客户端,我需要能够提取x_len和y_len并且可以读取x和y。
#TODO:perform base64 decoding
x_len = int(test_string[0])
x = test_string[:x_len]
I get the following error: ValueError: invalid literal for int() with base 10: '\x05'
我收到以下错误:ValueError:int()的基数为10的无效文字:'\ x05'
I assume the argument of int is in hex so I probbaly need to do some decoding before passing to the int. Can someone give me a pointer as to what function to use from decode or if there is any easier way to accomplish this?
我假设int的参数是十六进制的,所以我可能需要在传递给int之前进行一些解码。有人可以给我一个指针,说明从解码中使用什么功能,或者有没有更简单的方法来完成这个?
2 个解决方案
#1
7
You probably want ord()
, not int()
, since ord()
is the opposite operation from chr()
.
你可能想要ord(),而不是int(),因为ord()是与chr()相反的操作。
Note that your code will only work for lengths up to 255
since that is the maximum chr()
and ord()
support.
请注意,您的代码仅适用于最大255的长度,因为这是最大的chr()和ord()支持。
#2
1
t="ABCDE"
print reduce(lambda x,y:x+y,[ord(i) for i in t])
#output 335
usage of ord: it is used to convert character to its ascii values ..
ord的用法:用于将字符转换为ascii值。
in some cases only for alphabets they consider A :1 --- Z:26 in such cases use
在某些情况下,他们只考虑字母A:1 --- Z:26在这种情况下使用
ord('A')-64
results 1 since we know ord('A')
is 65
ord('A') - 64结果1因为我们知道ord('A')是65
#1
7
You probably want ord()
, not int()
, since ord()
is the opposite operation from chr()
.
你可能想要ord(),而不是int(),因为ord()是与chr()相反的操作。
Note that your code will only work for lengths up to 255
since that is the maximum chr()
and ord()
support.
请注意,您的代码仅适用于最大255的长度,因为这是最大的chr()和ord()支持。
#2
1
t="ABCDE"
print reduce(lambda x,y:x+y,[ord(i) for i in t])
#output 335
usage of ord: it is used to convert character to its ascii values ..
ord的用法:用于将字符转换为ascii值。
in some cases only for alphabets they consider A :1 --- Z:26 in such cases use
在某些情况下,他们只考虑字母A:1 --- Z:26在这种情况下使用
ord('A')-64
results 1 since we know ord('A')
is 65
ord('A') - 64结果1因为我们知道ord('A')是65