Reputation: 760
I am trying to read a txt file which has hexadecimal data. I Want to convert them in decimal except one column which I want to convert into binary bits and write them in 8 separate columns. Sample data set
1/4/2010 15:31 <00000> 0x0001 0x0010 0x0014 0x0000 0x0142 0x0001 0x0001 0x0000 0x028F 0x2007 0x0105 0x00AA 0x005A 0xFA8C 0xFACD 0xFAED 0x003B 0xFFA3 0xFFDE 0x0080 0xFEE0 0xFF2E 0x0000 0x0108 1/4/2010 15:31 <00000> 0x0001 0x0010 0x0014 0x0000 0x0143 0x0001 0x0001 0x0000 0x028F 0x2008 0x0105 0x00AA 0x005B 0xFA8C 0xFACC 0xFAEE 0x003C 0xFFA3 0xFFDE 0x0080 0xFEE0 0xFF2E 0x0000 0x0108 1/4/2010 15:31 <00000> 0x0001 0x0010 0x0014 0x0000 0x0144 0x0001 0x0001 0x0000 0x028F 0x2009 0x0105 0x00A9 0x005C 0xFA8C 0xFACC 0xFAF0 0x003B 0xFFA3
clear all; %
[b,pathb]=uigetfile({'*.txt'},'Select the file','C:\Data\2010');
file2=[pathb b];
data=dlmread('file2', '\t', 2, 1);
newdata=hex2dec(data);
Now I do not know how to get rid of 0x in all the values and I need to convert the last column into binary and write in 8 columns.
Any help is highly appreciated. thanks
Upvotes: 1
Views: 6109
Reputation: 125854
Here's a slightly different tack you could try, using TEXTSCAN to read all the data first as strings:
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
If you have N rows in your file, you should end up with:
dates
of date strings (which can be converted to either serial date numbers or date vectors).decValues
containing the converted decimal values. The values were converted from the range 0 to 65535 (i.e. unsigned 16-bit integer) to -32768 to 32767 (i.e. signed 16-bit integer) using two's complement.binValues
containing the converted binary values. Each cell contains a 1-by-8 character string of zeroes and ones.Upvotes: 1