简体   繁体   中英

Insert hex value in the middle of a string python

I want to create 5 hex bytes length string that is gonna be send through a socket. I want that send 255 packets changing the third byte incremntally. How can I do that? Something like this code:

i=0    
while True:
        a="\x3f\x4f"+hex(i)+"\x0D\x0A"
        socket.send(a)
        i=i+1

The problem is that this code is introducing 0x0 (30 78 30) instead of 00 in the first loop for example.

Thank you

I think you're a bit confused here.

\\x3f is a single character (the same character as ? ).

If i is, say, 63 (hex 3F), you don't want to add the separate characters \\\\ , x , 3 , and f to the string, you want to add the single character \\x3f . Likewise, if it's 0 (hex 00), you don't want to add the separate characters \\\\ , x , 0 to the string, you want to add the single character \\x0 .


That's exactly what the chr function is for:

Return a string of one character whose ASCII code is the integer i . For example, chr(97) returns the string 'a'


By contrast, the function hex will:

[c]onvert an integer number (of any size) to a lowercase hexadecimal string prefixed with “0x”…

So, hex(97) returns the four character string '0x61' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM