As the error message states, if fromstring is fed binary input data, the data length must be a multiple of the element size. This is also stated in the documentation. In your case, the element size is 2, because a uint16 is composed of two bytes. However in your second string, w1, you only provide 1 byte. One way to solve this problem is to add a leading zero to the smaller number:
import numpy as np
raw=b''
w="\x01\x02 \x01\x02"
w1="\x01\x03 \x04"
elements=w.split(' ')+w1.split(' ')
raw=b''.join(['\x00'+e if len(e)==1 else e for e in elements ])
results = np.fromstring(raw, dtype=np.uint16)
print results
This outputs:
[ 513 513 769 1024]
For me this result was surprising. Apparently the bytes are read from left to right (smallest to biggest). I don't know if this is platform specific (I'm on osx) or always like this in numpy. Anyway, if your desired byte order is from right to left, you can reverse the order like so:
raw2=b''.join([e+'\x00' if len(e)==1 else e[1]+e[0] for e in elements])
results2 = np.fromstring(raw2, dtype=np.uint16)
print results2
which results in:
[258 258 259 4]
len(raw)? I'm guessing 7.w1only has 3 bytes (after removing the space).\x00before\x04?). If that is not possible, why don't you do it without replacing the spaces and instead doresutl = np.fromstring(raw, dtype=int, sep=' ').astype(uint16)?