登录论坛

查看完整版本 : 从十六进制到二进制和十进制


poster
2019-12-10, 20:48
我正在尝试读取具有十六进制数据的txt文件。我想将它们转换为十进制,但我要将其转换为二进制位并将其写入8个单独的列中。样本数据集

1/4/2010 15时31 0×0001 0×0010 0×0000 0x0014 0x0001的0x0142 0x0001的0×0000 0x028F 0x2007 0x0105 0x00AA 0x005A 0xFA8C 0xFACD 0xFAED 0x003B 0xFFA3 0xFFDE 0x0080 0xFEE0 0xFF2E为0x0000 0x0108 1/4/2010 15时31 0×0001 0×0010 0×0000 0x0014 0x0143 0x0001的0×0001 0×0000 0x028F 0x2008 0x0105 0x00AA 0x005B 0xFA8C 0xFACC 0xFAEE 0x003C 0xFFA3 0xFFDE 0x0080 0xFEE0 0xFF2E为0x0000 0x0108 1/4/2010 15点31 0×0001 0×0010 0×0000 0x0014 0x0001的0x0144 0x0001的0×0000 0x028F西班牙语 - 秘鲁0x0105 0x00A9 0x005C 0xFA8C 0xFACC 0xFAF0 0x003B 0xFFA3

清除所有%

[b,pathb] = uigetfile({'*。txt'},'选择文件','C:\ Data \ 2010');

file2 = [路径b];

data = dlmread('file2','\ t',2,1);

newdata = hex2dec(data);

现在我不知道如何摆脱所有值中的0x,我需要将最后一列转换为二进制并写入8列。

非常感谢您的帮助。谢谢



回答:

您可以尝试使用稍有不同的方法,使用TEXTSCAN (http://www.mathworks.com/help/techdoc/ref/textscan.html)首先读取所有数据作为字符串:

fid = fopen(file2,'rt'); %# Open the file str = ['%s %s %s ' repmat('0x%s ',1,24)]; %# Format string for columns C = textscan(fid,str,'CollectOutput',1); %# Read all fields as strings %# (removing 0x's) fclose(fid); %# Close the file C = C{1}; %# Remove outer cell encapsulation dates = strcat(C(:,1),{' '},C(:,2)); %# Collect the date strings decValues = cellfun(@hex2dec,C(:,4:end-1)); %# Convert the first 23 columns to %# decimal values decValues = decValues-65536.*(decValues > 32767); %# Change from unsigned to %# signed 16 bit values binValues = cellfun(@(n) dec2bin(hex2dec(n),8),... %# Convert the last column C(:,end),'UniformOutput',false); %# to binary strings 如果文件中有N行,则应该以:


日期字符串的N×1单元格数组dates (可以将其转换为序列日期数字 (http://www.mathworks.com/help/techdoc/ref/datenum.html)或日期向量 (http://www.mathworks.com/help/techdoc/ref/datevec.html) )。
包含转换后的十进制值的N×23数组decValues 。使用二进制补码 (http://en.wikipedia.org/wiki/Signed_number_representations#Two.27s_complement)将值从0到65535(即无符号的16位整数)到-32768到32767(即有符号的16位整数)范围内进行转换。
包含转换后的二进制值的N×1单元格数组binValues 。每个单元格都包含一个由零和一组成的1×8字符串。


更多&回答... (https://stackoverflow.com/questions/4310225)