0

I've got two bytes-type variable that I've concatenated (separated by a space) so I can send it as one variable to a server (socket programming). What I'm trying to figure out is how to then separate them and assign them to their original variables using regular expressions. I've consulted regular expressions parsing a binary file but it wouldn't work for me. Here is my output after trying the expression as so just to get the cipher variable

ciphertext = re.match(b'\S', ciphertext)

It generally only matches the first couple characters and returns an object, which isn't what I'm wanting. What am I doing wrong?

edit: I'm probably doing it the hard way. Honestly, any recommendation on how to send 2 bytes objects over a socket using UDP. Its proving really difficult

  • Please include your output in your question, not as a link to a screenshot. – Ian McLaird Dec 05 '17 at 20:05
  • But in summary, the reason you're getting an object is because that's what `re.match` returns. It gives you back a `match object` (or `None` if the string doesn't match) which allows you to work with the matching text. I'm not entirely sure what you were expecting that call to do. – Ian McLaird Dec 05 '17 at 20:07

2 Answers2

1

Ended up using str.rpartition to solve my problems. Wasn't the most obvious answer, but it worked.

0

Why are you using regex to do this?. You should take a look at the struct module:

In [1]: import struct

In [2]: magic = b'\xcf\xfa\xed\xfe'

In [3]: decoded = struct.unpack('<I', magic)[0]

In [4]: hex(decoded)
Out[4]: '0xfeedfacf'

Also, you can use this recipe for decoding binary files

franvergara66
  • 10,524
  • 20
  • 59
  • 101
  • Can I use structs to combine two byte objects into one variable that can later be re-separated? If i could copy the whole value from each variable and put them into a struct, that would be perfect, but it keeps clipping the values. – Fullmetal7777 Dec 05 '17 at 21:07