Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse one logical bit in Matlab

Does it exist a better way to reverse an element of X?

>> X = dec2bin(10)
X = 1010

I did this:

x(i) = num2str(1-str2num(x(i)))
like image 960
Academia Avatar asked Jan 10 '12 19:01

Academia


People also ask

How do you reverse a logical vector in Matlab?

Method 1: By using flipud() function The flipud() function is used for flipping the specified vector's elements. Here, flipud(A) function is used to return a vector with reversed elements of the same length of the specified vector “A”. Example 1: Matlab.

How do you invert a logical array?

We can also use the Tilde operator (~) also known as bitwise negation operator in computing to invert the given array. It takes the number n as binary number and “flips” all 0 bits to 1 and 1 to 0 to obtain the complement binary number.


2 Answers

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

bitset( x, bitNumber)

In case 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));

It is better, because you don't need to convert the number to char .

like image 199
Andrey Rubshtein Avatar answered Sep 29 '22 20:09

Andrey Rubshtein


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

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

However, if you do want to operate on the character array, you could also do this very strange thing:

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

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

like image 34
gnovice Avatar answered Sep 29 '22 22:09

gnovice