Inverse one logical bit in Matlab

Is there a better way to change an element of X?

>> X = dec2bin(10) X = 1010 

I have done this:

 x(i) = num2str(1-str2num(x(i))) 
+6
source share
2 answers

If you want to flip the bit of the num numeric value without first converting it to an array of characters '0' and '1' , then you can use functions such as BITXOR , BITGET and BITSET (as Andrey also mentions ):

 num = bitxor(num, 4); %# Flip the bit in the 4 place (ie bit 3) %# Or ... num = bitset(num, 3, ~bitget(num, 3)); %# Flip bit 3 

However, if you want to work with an array of characters, you can also do this very weirdly:

 X(i) = 'a' - X(i); %# Or ... X(i) = 97 - X(i); 

This works because characters 'a' and X(i) first converted to their Unicode equivalent UTF-16 numeric values ​​before the mathematical operation is performed. Since the numerical value for 'a' is 97, then a '0' (numerical value 48) or '1' (numerical value 49) subtracted from 'a' will result in a numerical value for the other. The resulting numerical value on the right side of the equation is then converted back to the character when it is put back into the character array X

+5
source

If I understand you correctly, and you want to set one bit to 1, use bitset

 bitset( x, bitNumber) 

If you want to flip a bit from 0 to 1 and vice verca, use bitxor

 num = bin2dec('101110'); bitNum = 1; res = bitxor(num, 2^(bitNum-1)); disp(dec2bin(res)); 

This is better because you do not need to convert the number to char .

+12
source

Source: https://habr.com/ru/post/905649/


All Articles