matlab读二进制文件代码,读取二进制文件:Matlab不同于R和python

我试图重新创建一个用R或python读取二进制文件的Matlab脚本。以下是指向test.bin数据的链接:

https://github.com/AndrewHFarkas/BinaryReadTest

FilePath = 'test.bin'

fid=fopen(FilePath,'r','b');

VersionStr=fread(fid,7,'char')

Version=fread(fid,1,'int16')

SizeFormat='float32'

DataFormat='float32'

EegMegStatus=fread(fid,1,SizeFormat)

NChanExtra=fread(fid,1,SizeFormat)

TrigPoint=fread(fid,1,'float32')

DataTypeVal=fread(fid,1,'float32')

TmpSize=fread(fid,2,SizeFormat)

AvgMat=fread(fid,1,DataFormat)

Matlab输出:

VersionStr =

86

101

114

115

105

111

110

Version =

8

SizeFormat =

'float32'

DataFormat =

'float32'

EegMegStatus =

1

NChanExtra =

0

TrigPoint =

1

DataTypeVal =

0

TmpSize =

65

1076

AvgMat =

-12.9650

这是我最近一次尝试使用python(我从另一个stackoverflow答案中发现了一些代码:

import numpy as np

import array

def fread(fid, nelements, dtype):

if dtype is np.str:

dt = np.uint8 # WARNING: assuming 8-bit ASCII for np.str!

else:

dt = dtype

data_array = np.fromfile(fid, dt, nelements)

data_array.shape = (nelements, 1)

return data_array

fid = open('test.bin', 'rb');

print(fread(fid, 7, np.str)) # so far so good!

[[ 86]

[101]

[114]

[115]

[105]

[111]

[110]]

#both of these options return 2048

print(fread(fid, 1, np.int16))

np.fromfile(fid, np.int16, 1)

不管我尝试过什么,我都不能得到任何相同的数字。我试过使用小端和大端的设置,但可能不正确。

newdata = file("test.bin", "rb")

version_char = readBin(newdata, "character", n=1)

version_char

[1] "Version" # this makes sense because the first 7 bytes to spell Version

version_num = readBin(newdata, "int", size = 1 , n = 1, endian = "little")

version_num

[1] 8 #correct number

比赛之后什么也没有。这让我很困惑,因为对于版本号,我只能得到8(字节)大小=1,但据我所知,int16应该是两个字节。我尝试了下面的代码,以便按照另一篇文章中的建议以浮点形式读取:

readBin(newdata, "double", size = 4 , n = 1, endian = "little")

谢谢大家抽出时间

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值