Borrar filtros
Borrar filtros

Flip last 3 bits of vector

1 visualización (últimos 30 días)
Jorge Zapata
Jorge Zapata el 14 de Mzo. de 2013
I have a uint16 vector which I need to flip the last 3 bits of every number.
I already have done this but I think there must be an easier solution to do this. Here is my code.
%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);
As you can see there are a lot of lines for a simple operation, I wonder if there is a more efficient method to do the same. Thanks

Respuesta aceptada

Teja Muppirala
Teja Muppirala el 14 de Mzo. de 2013
You can use BITXOR,
V = uint16( round(65535*rand(5,1)) );
V2 = bitxor(V,1+2+4); % 1+2+4 = 7 = 0000000000000111
dec2bin(V)
dec2bin(V2)
  2 comentarios
Jan
Jan el 14 de Mzo. de 2013
+1, I cannot stress enough how much better this is compared to the dec2bin conversion tricks. Converting numerical data to strings for a manipulation is too indirect to be efficient.
Jorge Zapata
Jorge Zapata el 14 de Mzo. de 2013
In fact strings operations affect performance so your answer is what I was looking for, thanks

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Productos

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by