位旋转操作

时间:2011-02-22 18:02:08

标签: matlab

有没有办法让Bit旋转操作可逆?我的意思是,如果存在图像X(大小256 * 256 * 3),则在进行位旋转时,获得图像Y.然后,对Y进行一次旋转,我们返回图像X.此外,如何解决位溢出,以免信息丢失。

2 个答案:

答案 0 :(得分:1)

更新:我已经采用了我在下面发布的代码并将其细化为a complete function,并带有错误检查,帮助文档以及对无符号整数数组进行操作的能力双精度变量就像相关的内置函数BITSHIFT一样。我建议使用上面链接到的较新版本而不是下面发布的旧版本。


MATLAB没有内置的位旋转功能,BITSHIFT函数会丢弃溢出的位。但是,您可以基于existing bit operations实现自己的位旋转功能。这是一个简单的第一遍版本,我把它放在一起(没有错误检查):

function data = bit_rotate(data,nBits)
  dataBits = log2(double(intmax(class(data)))+1);  %# Number of bits in data
  nBits = rem(nBits,dataBits);  %# No need to rotate by dataBits bits or more
  if nBits == 0  %# No bit rotation needed, just return
    return
  end
  shiftedData = bitshift(data,nBits);              %# Bit shift the data
  lostData = bitxor(data,bitshift(shiftedData,-nBits));  %# Find the lost bits
  rotatedData = bitshift(lostData,nBits-sign(nBits)*dataBits);  %# Rotate them
  data = shiftedData+rotatedData;  %# Add the rotated bits to the shifted bits
end

以下是一些测试数据:

>> B = uint8(208);     %# An unsigned 8-bit integer value
>> disp(dec2bin(B,8))  %# Display the bit pattern of B
11010000
>> disp(dec2bin(bit_rotate(B,2),8))   %# Rotate left by 2 bits
01000011
>> disp(dec2bin(bit_rotate(B,-2),8))  %# Rotate right by 2 bits
00110100

请注意bit_rotate也可以对data的任何大小矩阵输入进行操作,只要它是无符号整数类型。

答案 1 :(得分:0)

当然,位旋转是可逆的,只需旋转相反的量即可。

维基百科有很好的信息,关于如何在C中实现基本位移,这样你就不会出现溢出: http://en.wikipedia.org/wiki/Circular_shift

我想如果在Matlab中将操作称为“位旋转”,那么它肯定不会溢出。

相关问题