简体   繁体   中英

How to convert 16bit binary file to 32bit file?

i have several 16bit binary files, that i need to convert into 32bit binary files in python.

i have tried the following:

        data16 = np.fromfile(data_dir+fn, dtype=np.uint16)
        print("16bit " + str(data16))

        convert = np.array(data16 * 256)
        print("32bit " + str(convert) + "\n")

Im new to dealing with datafiles and bytes etc. but from what i have read in the past few hours, this should work, shouldnt it?

based on the output that i have read, it seems to work in some parts but not in others... quite confusing..

Here is the output:

16bit [41238   273   257 ... 65456 65472 65482]
32bit [ 5632  4352   256 ... 45056 49152 51712]

16bit [41238   273   769 ...     4     1 65521]
32bit [ 5632  4352   256 ...  1024   256 61696]

16bit [41238   273   513 ...    52    75    67]
32bit [ 5632  4352   256 ... 13312 19200 17152]

Here a portion of the bits (files are huge, pycharm only prints some out). In the last row the last 3 bits are correctly converted but not all of the bits, why is that?

You are seeing an integer overflow. The maximum value that np.uint16 can represent is 2^16 = 65536.

41238 * 256 is much larger than 2^16. The value you get is 41238 * 256 % 2^16.

To avoid the overflow, convert your numbers to np.uint32, and then multiply by 256:

convert = data16.astype(np.uint32) * 256

Note that you are converting to a 24 Bit range with your 2^8 multiplication factor, not to a 32 Bit range.

import numpy as np

data16 = np.fromfile(data_dir+fn, dtype=np.uint16)
print("16bit " + str(data16))

data32 = data16.astype(dtype=np.uint32) * 256
print("32bit " + str(data32))

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