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

조회 수: 2 (최근 30일)
fiona rozario
fiona rozario 2017년 6월 2일
댓글: fiona rozario 2017년 6월 3일
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?

답변 (2개)

Joseph Cheng
Joseph Cheng 2017년 6월 2일
편집: Joseph Cheng 2017년 6월 2일
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
fiona rozario
fiona rozario 2017년 6월 3일
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.

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


Guillaume
Guillaume 2017년 6월 2일
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

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by