Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting character to int and vice versa in Python

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.

#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'

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?

like image 545
as3rdaccount Avatar asked Mar 25 '26 05:03

as3rdaccount


2 Answers

You probably want ord(), not int(), since ord() is the opposite operation from chr().

Note that your code will only work for lengths up to 255 since that is the maximum chr() and ord() support.

like image 115
Amber Avatar answered Mar 26 '26 17:03

Amber


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 ..

in some cases only for alphabets they consider A :1 --- Z:26 in such cases use

ord('A')-64 results 1 since we know ord('A') is 65

like image 23
sundar nataraj Avatar answered Mar 26 '26 18:03

sundar nataraj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!