且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

扭转在Matlab一个逻辑位

更新时间:2023-11-03 23:52:52

如果你想翻转位数值 NUM 的没有首先将其转换成一个字符数组的 0 1 ,那么你可以使用类似的 BITXOR ,的 BITGET BITSET 一>(如安德烈也提到):

  NUM = BITXOR(NUM,4); %#翻转在4的位置的位(即第3位)
%# 要么 ...
NUM =位集(NUM,3〜bitget(NUM,3)); %#翻转位3

然而,如果你的的想要的字符数组进行操作,你也可以做到这一点很奇怪的事情:

  X(I)='A' -  X(I)
%# 要么 ...
X(ⅰ)= 97 - X(ⅰ);

这工作,因为字符 'A' X(I)首先被转换为它们的等效统一code UTF-16的数值前的数学运算是执行。由于对数值'A' 97,那么 0 (数值48)或 1 (数值49)从'A'将导致其他的数值。在等式当它被放回到字符数组中然后转换回为字符的右手侧将所得数值 X

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)))

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.