1

I have a 1D array of integers read in from a binary via

data = np.fromfile(file.dat, 'u1')

where data returns

array([242, 255, 101, 0, 124, 0, 86, 0, 33, 0, 
       112, 0, 32, 1, 74, 1, 195, 0, 16, 0], dtype=uint8)

The 0's in the series represent extra bits used for values over or under the standard 256. For example the 244 at index 0 should be -14 and is represented by 255 (or 256) - 242. Conversely the value at index 13 - reading as 32 is actuality 256 + 32, or 288. I'm trying to get the above array to look like --

[-14, 101, 124, 86, 33, 112, 288, 330, 195, 16]

I think I want something that uses the index and the value to evaluate the preceding value, if values 1 or 255 are found.

I've started with the below, but lost the thread at the end of the day.

for i, a in enumerate(data):
    if a == 255:
       neg = i,a

If anyone can recommend a better way to handle binary values I'm open to learning about that as well. Help appreciated!

2
  • What does lost the thread at the end of the day. mean? Commented May 14, 2019 at 0:45
  • Ha, it's a euphemism for being tired Commented May 14, 2019 at 1:42

1 Answer 1

1

You can viewcast to '<i2'(< stands for little endian, i for signed integer and 2 for 2 bytes)

x = np.array([242, 255, 101, 0, 124, 0, 86, 0, 33, 0, 
       112, 0, 32, 1, 74, 1, 195, 0, 16, 0], dtype=np.uint8)

x.view('<i2')
# array([-14, 101, 124,  86,  33, 112, 288, 330, 195,  16], dtype=int16)

Or you can use '<i2' directly with fromfile.

Sign up to request clarification or add additional context in comments.

Comments

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.