How can I change the LSBs of consecutive elements of an array?

2 views (last 30 days)
I have a row matrix a = [23, 255, 67, 89, 45, 90, 34, 12] and a number, n = 3 (of 8 bits) which I want to hide in the LSBs of every element. 3 is '00000011', so LSB of 23 should change to 0 (if not already 0), LSB of 255 should change to 0 and so on till 12. n is a variable from 2-8 of 8 bits.
I tried the following code:
n=3;
a=[23, 255, 67, 89, 45, 90, 34, 12];
str=dec2bin(n,8);
for i=1:8
b(1,i)=bitset(a(1,i),8,str(i));
end
I get the following error: ASSUMEDTYPE must be an integer type name.
How do I convert the string 'str' to be a numeric array of the 1s and 0s?

Answers (2)

Joseph Cheng
Joseph Cheng on 2 Jun 2017
Edited: Joseph Cheng on 2 Jun 2017
you could use bitand()
a = [23, 255, 67, 89, 45, 90, 34, 12]';
n=3;
b = bitand(a ,255-n,'uint8')
disp(dec2bin(a))
disp('zeroed out last 2 bits')
disp(dec2bin(b))
i know i didn't implement your selection of n correctly as i wasn't able to follow what you were describing with lsbs of 3 and the 23 example, however the bit wise operators should work whatever you're trying to describe
  1 Comment
fiona rozario
fiona rozario on 3 Jun 2017
n is a user input, so suppose n = 3, in binary - '00000011' (stored in 'str'). a(1) = 23 or '00010111'.
What I want to do is change the least significant bit of a(1) from 1 to whatever is the first bit of n; in this case - '0'. So, a(1) in binary should change to '00010110' (22 in decimal). Similarly, the least significant bit of 255 should be changed to whatever is the second bit of n....and so on till the eighth element of the array, a.

Sign in to comment.


Guillaume
Guillaume on 2 Jun 2017
The third argument of bitset must either be the number 0 or 1 or a char array representing a valid type (such as 'uint8'). You're giving it the char '0' or '1'. Change your line to:
b(1, i) = bitset(a(1, i), 8, str(i) - '0'); %or str(i) == '1', whichever you prefer

Tags

Community Treasure Hunt

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

Start Hunting!