user8192913
user8192913

Reputation: 23

How to use bitset function in MATLAB to modify multiple bits simultaneously

>> a = 255

a =

   255

>> bitset(a,1,0)

ans =

   254

here the first bit is set to 0 so we get 11111110 equivalent to 254

>> bitset(a,[1,2],0)

ans =

   254   253

here the 1st bit and 2nd bit are being set to 0 seperately. Hence we get 11111110 equivalent to 254 11111101 equivalent to 253

how to get 11111100 equivalent to 252?

Upvotes: 2

Views: 1166

Answers (4)

Richard Munro
Richard Munro

Reputation: 1

Here is a little recursive function based on the answer from @Mad Physicist that will allow zeroing of any number of bits in data . Thanks for the original info. The recursion is probably dead obvious to most people but it might help somebody out.

function y = zero_nbits(x, n)

   y = bitset(x, n, 0)

   if n > 1
      y = zero_nbits(y, n-1);
   end

end

Upvotes: 0

TallBrianL
TallBrianL

Reputation: 1252

Maybe most explicit, easiest to understand, you can convert to a string representing binary and then do the operations there, then convert back.

a = 255
bin_a = flip(dec2bin(a))  % flip to make bigendian
bin_a([1, 2]) = '0'
a = bin2dec(flip(bin_a))

Upvotes: 1

Mad Physicist
Mad Physicist

Reputation: 114310

Apply bitset twice:

bitset(bitset(a, 1, 0), 2, 0)

The order of application should not matter.

Alternatively, you can use the fact that bitset is an equivalent to applying the correct sequence of bitand, bitor and bitcmp operations.

Since you are interested in turning off multiple bits, you can do

bitand(bitset(a, 1, 0), bitset(a, 2, 0))

Upvotes: 1

Cris Luengo
Cris Luengo

Reputation: 60504

Here's a one-liner:

a = 255;
bits = [1,2];
bitand(a,bitcmp(sum(2.^(bits-1)),'uint32'))

Taken apart:

b = sum(2.^(bits-1))

computes the integer with the given bits set. Note that bits must not contain duplicate elements. Use unique to enforce this: bits = unique(bits).

c = bitcmp(b,'uint32')

computes the 32-bit complement of the above. ANDing with the complement resets the given bits.

bitand(a,c)

computes the binary AND of the input number and the integer with the given bits turned off.

Setting bits is easier:

a = 112;
bits = [1,2];
bitor(a,sum(2.^(bits-1)))

Upvotes: 1

Related Questions