[英]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. 我有几个16位二进制文件,我需要在python中将其转换为32位二进制文件。
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). 这里有一部分位(文件很大,pycharm只打印出一部分)。 In the last row the last 3 bits are correctly converted but not all of the bits, why is that?
在最后一行中,最后3位被正确转换,但不是所有位都正确转换,为什么呢?
You are seeing an integer overflow. 您正在看到整数溢出。 The maximum value that np.uint16 can represent is 2^16 = 65536.
np.uint16可以表示的最大值是2 ^ 16 = 65536。
41238 * 256 is much larger than 2^16. 41238 * 256远大于2 ^ 16。 The value you get is 41238 * 256 % 2^16.
您得到的值为41238 * 256%2 ^ 16。
To avoid the overflow, convert your numbers to np.uint32, and then multiply by 256: 为避免溢出,请将数字转换为np.uint32,然后乘以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. 请注意,您将使用2 ^ 8乘法因子转换为24位范围,而不是32位范围。
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.