【问题标题】:Flip last 3 bits of vector翻转向量的最后 3 位
【发布时间】:2013-03-02 07:59:10
【问题描述】:

我有一个 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);

正如你所见,一个简单的操作有很多行,我想知道是否有更有效的方法来做同样的事情。

【问题讨论】:

    标签: matlab binary


    【解决方案1】:

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

    V = bitxor(V, 7);
    

    【讨论】:

    • 7 在二进制中是 111,即三个最低有效位 :)
    • 这绝对是我正在寻找的答案,谢谢:)
    • +1。如果您想传递更易读的位掩码参数,您仍然可以使用bin2dechex2dec 以二进制或十六进制字符串的形式提供参数:bitxor(V, bin2dec('0000 0111'))。 (顺便说一句,“bin2dec”、“dec2bin”和它们的亲属的名称具有误导性;它们确实将字符串转换为(二进制)数字,反之亦然。)
    猜你喜欢
    • 2023-04-08
    • 1970-01-01
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    • 2017-05-30
    相关资源
    最近更新 更多