user1285419
user1285419

Reputation: 2225

how to convert an arrary of 16-bit unsigned intergers into ascii string in matlab

I am looking for a way to convert an array of 16-bit unsigned integer into ASCII char array. I am using char to do the conversion

D=[65 65 65 65];
char(D)

which will show 4 'A'. However, since each number in D is 16-bit, I expect it to convert each number to 2 chars. For example, if I have

D=[16707]
char(D)

I expect it gives me two chars 'A' and 'C'. But char always return 1 character. Is that anyway to force char to convert like the way I stated? Thanks.

Upvotes: 1

Views: 2140

Answers (3)

Luis Mendo
Luis Mendo

Reputation: 112689

Use typecast to convert each uint16 to two uint8, and then apply char. Make sure that the input to typecastr is really of type uint16.

If you need to reverse char order, use swapbytes on the uint16 vector.

>> D = [16707 16708];

>> char(typecast(uint16(D),'uint8'))
ans =
CADA

>> char(typecast(swapbytes(uint16(D)),'uint8'))
ans =
ACAD

Upvotes: 0

Buddhima Gamlath
Buddhima Gamlath

Reputation: 2328

For this, you need to write your own function.

You can use char() to convert most significant byte and least significant byte separately.

k      = 16707;
first  = char(bitand(bitshift(k, -8), 255));
second = char(bitand(k, 255));

Upvotes: 1

Shachaf.Gortler
Shachaf.Gortler

Reputation: 5735

Have a look at http://www.mathworks.com/help/matlab/ref/char.html

It cleatly states that the char function is valid only for 8 bit numbers. you can convert each part of cell of the array with this and contact the results for each two cells.

Upvotes: 0

Related Questions