Interpreting character array as hex data

Hi
I want to write a MAC address to a flash device. The address is generated by matlab and is in hex format, but strored as a character array (see code). When I write the variable to a binary file, matlab converts the characters to binary which is not what I want as my data already is hex formated.
macAddr = '0050c246d880';
fid = fopen('macAddr.bin','w');
fwrite(fid, macAddr);
fclose(fid);
% file content: "30 30 35 30 63 32 34 36 64 38 38 30" (hex interpreted)
I solved this problem by splitting the address into bytes and converting them to decimal:
macAddr = '0050c246d880';
% Split address to bytes and store them as decimal numbers
macAddrDec = '';
for i=1:length(macAddr)/2
macAddrDec(i) = hex2dec(macAddr(i*2-1:i*2));
end
fid = fopen('macAddr.bin','w');
fwrite(fid, macAddrDec);
fclose(fid);
% file content: "00 50 c2 46 d8 80" (hex interpreted)
This works, but isn't there an easy way to tell matlab that a character array is already hex formatted?
Cheers Simon

답변 (2개)

Walter Roberson
Walter Roberson 2012년 2월 13일

0 개 추천

You are mistaken in your interpretation that the data is being stored in hex in the file. The data is stored in binary and some program you are using is showing you the hex equivalent of the binary.
The character string is in the character representation of hex, not hex itself, and needs to be interpreted as binary in order to write it, using logic such as you have come up with.

댓글 수: 2

Simon
Simon 2012년 2월 13일
Yes of course, you are right, I always forget that TextPad shows me the hex interpretation of binary files. I would still have hoped that there would have been a smarter way to achive my goal.
Walter Roberson
Walter Roberson 2012년 2월 13일
fwrite(fid, sscanf(macAddr, '%2x'));
which is merely a more compact way and not a smarter way.

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

Jan
Jan 2012년 2월 13일

0 개 추천

You can write the data in CHAR format:
macAddr = '0050c246d880';
fid = fopen('macAddr.bin','w');
fwrite(fid, macAddr, 'char');
fclose(fid);
Walter suggested sscanf for the conversion from HEX to DEC already: This is much faster than hex2dec.

댓글 수: 1

Simon
Simon 2012년 2월 13일
What output do you get with this? I get the same as without this option and that is not what I want.

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

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

질문:

2012년 2월 13일

Community Treasure Hunt

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

Start Hunting!

Translated by