# How to convert 24-bit signed hex from .csv file to an array of decimal data?

17 views (last 30 days)
Neo on 23 Jul 2019
Commented: Neo on 23 Jul 2019
The csv file has content like below, the hexical data is signed 24-bit and has 0x prefix:
============
DATA
0xfd22cc
0xfe89d1
0xff8d8b
0x004b41
0x00d9d5
0x0125fa
==============
I have a few challenges, not quite good with coding with Matlab:
1) How to get rid of 0x prefix?
2) How to convert the signed 24-bit hex to decimal?
I came up with a really ugly code to do the work, but would love to learn a elegant way:
dat1 = table2array(dat(:,1));
out = strip(dat1,'left','0');
out = strip(out,'left','x');
out_dec = typecast(uint32(base2dec(out, 16)), 'int32');
for i=1:length(out_dec)
if out_dec(i) < 2^23
out_signed(i) = out_dec(i);
else
out_signed(i) = out_dec(i) - 2^24;
end
end

Jan on 23 Jul 2019
data = table2array(dataTable(:,1));
data = strrep(data, '0x', '');
I prefer the faster sscanf to convert hex strings to decimals.

Guillaume on 23 Jul 2019
Note that:
data = table2array(dataTable(:,1));
is simply:
data = dataTable{:, 1};
%or
data = dataTable.(1);
%or
data = dataTable.Data;
Neo on 23 Jul 2019

Guillaume on 23 Jul 2019
Edited: Guillaume on 23 Jul 2019
I agree with Jan that sscanf is nicer and for that reason:
dataDec = rowfun(@(s) sscanf(s, '%x'), dataTable, 'ExtractCellContents', true, 'OutputFormat', 'uniform')