Maan Muafak Altohafe
Maan Muafak Altohafe

Reputation: 21

Convert logical to string

I need to convert logical vector to string .. so i can take each 8 bits of the logical vectors and convert it to it's equevilant of char ..

A=0 1 1 1 0 1 1 0 1 1 0 0 0 0 1 ;
A is of type logical 

i need to convert it to a string , so A will equal 'va'

Upvotes: 2

Views: 13379

Answers (2)

yuk
yuk

Reputation: 19880

In addition to @mathematical.coffee answer, instead of SPRINTF you can simply add 48 (which is code for character '0') to A to get the string:

Astr = char(A + 48);

or

Astr = char(A + int8('0'));

You can also use BIN2DEC instead of BASE2DEC.

So you can use it in ARRAYFUN as

arrayfun( @(i) char(bin2dec(char(A(i:(i+7))+48))),1:7:length(A) )

Upvotes: 0

mathematical.coffee
mathematical.coffee

Reputation: 56935

You can use char to convert a number to a character.

To convert each 8 elements of A into a number, there are a few methods:

% using definition of binary
n = sum(A(1:8).*2.^[7:-1:0])
% using 'base2dec'
n = base2dec(sprintf('%i',A(1:8)),2)

Then use char(n) to get the character out.

To apply this to every 8 elements of A you could use a loop or something like arrayfun.

arrayfun( @(i) char(base2dec(sprintf('%i',A(i:(i+7))),2)),
          1:8:length(A) )

Note The A you gave in your original question has only 15 elements so you can't really group every 8 (need 16) - you will need to write some code to deal with what to do in this case.

Helpful docs:

Upvotes: 2

Related Questions