0

I want to convert a bytearray type or a list of binary strings in python to a signed short list. In fact, I am getting a byte stream from Ethernet and I want to convert them in signed short; however, the only way I found in Python is using struct.unpack which seems to be slow since it requires a format string to determine the type of each byte.

This format requirement slows in two steps:

1) Required to make a long string for a long array of bytes

2) Required to search one-by-one in the array.

In C++, the following simple code does the job on the entire memory block contained by InBuf:

OutBuf = short int[len]
InBuf = char[len*2]
memcpy(&OutBuf, &InBuf, len*2)

This skips doing the format search within the byte array as well as the format string construction. Does anyone know a better way to do so in Python?

1 Answer 1

1

If you're using Python > 3.2 you could use int.from_bytes:

int.from_bytes(b, byteorder='little', signed=True)
Sign up to request clarification or add additional context in comments.

1 Comment

This does not work since I have a binary string or a list of binary strings likeMyBin = b'12wda121q' or MyBin = [b'12was',b'1231ws'] and int.from_bytes should be applied on the 2-byte slices to get the true conversion I need. This is still very slow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.