Conversion of ascii and hex

I hav hex data that to be sent through rs232 as ascii. In the same way, received ascii data in rs232 has to be converted into hex. But in matlab,no hex to ascii and ascii to hex conversion is available. Pls help me to do so......

Answers (4)

Mark Shore
Mark Shore on 13 May 2011
dec2hex(uint8('a'))
char(hex2dec('61'))
Also consult the documentation on character arrays.
Jan
Jan on 13 May 2011
Much faster than HEX2DEC:
sscanf('61', '%x') % 97
sscanf('abcd', '%x') % 43981
sscanf('abcd', '%2x') % [171;205]
And if you recieve the values from the serial port, FSCANF can convert from HEX directly.
EDITED: (Consider Walter's and my comments) For a direct conversion of the ASCII character to a HEX number and backwards:
sprintf('%x', 'M'); % '4d'
char(sscanf('%x', '4d')); % 'M'
Works with FPRINTF directly also.

5 Comments

It may be faster, but the OP was likely looking for specific ascii to hex conversion as per the ascii standard where, for example, 'M' = 4D and 'm' = 6D. http://www.asciitable.com/
As well, it's not clear to me how you would reverse the operation using this method.
Jan
Jan on 14 May 2011
@Mark: What about this:
sprintf('%x', double('M')) % '4d'
sprintf('%x', double('m')) % '6d'
And the other way around:
char(sscanf('4d', '%x')) % 'm'
Or if you want upper case with '%X'.
You don't even need the double()
sprintf('%x','M')
Those work nicely. For longer ascii strings you'd have to break up the multicharacter hex string into two character increments to go back to ascii, but that shouldn't be much of a problem.
It's a little odd that there's no direct conversion available and that all of the suggestions so far have been workarounds.
Mark, a minor variation on my earlier solution solves the break-up issue:
char(sscanf(String,'%2X').')
The original poster has not been back to clarify what they were looking for, so I would hesitate to say the suggestions are "workarounds".

Sign in to comment.

Titus Edelhofer
Titus Edelhofer on 13 May 2011

0 votes

Hi,
what about dec2hex and hex2dec/hex2num?
Titus
How is your hex data represented? If it is a vector of numbers each of which has an integer value 0 to 15, then
fprintf(s,'%X', YourVector)
and you would read it with
fscanf(s,'%1X')
Or, more likely,
sscanf(fgetl(s),'%1X')

1 Comment

If you are working with a string that is an even number of bytes, you could use
char(hex2dec(reshape(String,2,[]).').')
I would expect, though, that char(sscanf(String,'%2X').') would be faster.

Sign in to comment.

Categories

Tags

Asked:

on 13 May 2011

Community Treasure Hunt

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

Start Hunting!