Reputation: 63
Is there a way to make the Bit rotation operation reversible? I mean, if there is an image X (size 256 * 256 *3) then on doing bit rotation, image Y is obtained. Then on subjecting Y to a bit rotation, we get back image X. Also, How to tackle the bit overflow so that there is no information loss.
Upvotes: 2
Views: 1776
Reputation: 125874
UPDATE: I've taken the code I posted below and refined it into a complete function with error-checking, help documentation, and the ability to operate on arrays of unsigned integers and double-precision variables just like the related built-in function BITSHIFT. I suggest using the newer version I link to above instead of the older version posted below.
MATLAB does not have a built-in bit rotation function, and the BITSHIFT function will drop bits that overflow. However, you could implement your own bit rotation function based on the existing bit operations. Here's a simple first-pass version I threw together (sans error-checking):
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
And here's some test data:
>> 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
Note that bit_rotate
will also operate on any size matrix input for data
as long as it's an unsigned integer type.
Upvotes: 1
Reputation: 303
Sure, bit rotation is reversible, just rotate the other way around by the same amount.
Wikipedia has nice info on how to implement it in C with basic bit shifts so that you don't get overflow: http://en.wikipedia.org/wiki/Circular_shift
And I suppose that if the operation is called "bit rotation" in Matlab, it surely doesn't overflow anyway.
Upvotes: 0