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)))
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.
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.
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 .
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With