翻转最后3位向量

Jor*_*ata 3 binary matlab

我有一个uint16向量,我需要翻转每个数字的最后3位.

我已经完成了这个,但我认为必须有一个更简单的解决方案来做到这一点.这是我的代码.

%Turn the vector to binary
V_bin = dec2bin(V,16);
for i=1:length(V)
  %Get the last 3 bits
  tmp = V_bin(14:end);
  %Convert the string to decimal
  tmpdec = bin2dec(tmp);
  %Do the flip
  tmpflip = bitcmp(uint8(tmpdec));
  %Flipped to binary
  tmpbin = dec2bin(tmpflip);
  %Replace the flipped bits in the original string
  V_bin(14:end) = tmpbin(6:end);
end
V = bin2dec(V_bin);
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,对于简单的操作有很多行,我想知道是否有更有效的方法来执行相同的操作.

Sim*_*zie 5

我不熟悉matlab,但bitxor函数看起来很适合你,即

V = bitxor(V, 7);
Run Code Online (Sandbox Code Playgroud)