필터 지우기
필터 지우기

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

조회 수: 10 (최근 30일)
Neo
Neo 2019년 7월 23일
댓글: Neo 2019년 7월 23일
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:
%% Read in data
dat = readtable('demo.csv');
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
Jan 2019년 7월 23일
dataTable = readtable('demo.csv');
data = table2array(dataTable(:,1));
data = strrep(data, '0x', '');
dataDec = base2dec(data, 16);
index = dataDec >= 2^23;
dataDec(index) = dataDex(index) - 2^24;
I prefer the faster sscanf to convert hex strings to decimals.
  댓글 수: 2
Guillaume
Guillaume 2019년 7월 23일
Note that:
data = table2array(dataTable(:,1));
is simply:
data = dataTable{:, 1};
%or
data = dataTable.(1);
%or
data = dataTable.Data;

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Guillaume
Guillaume 2019년 7월 23일
편집: Guillaume 2019년 7월 23일
I agree with Jan that sscanf is nicer and for that reason:
dataTable = readtable('demo.csv');
dataDec = rowfun(@(s) sscanf(s, '%x'), dataTable, 'ExtractCellContents', true, 'OutputFormat', 'uniform')
dataDec(dataDec > 2^23) = dataDec(dataDec > 2^23) - 2^24;

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by