[C] Rotação de Bits

Publicado por Enzo de Brito Ferber (última atualização em 11/07/2017)

[ Hits: 10.018 ]

Homepage: http://www.maximasonorizacao.com.br

Download rotatebits.c

Download rotate_bits.c (versão 2)




Programa com uma função de rotação de bits.

Exemplo:

rotatebits( 0010, 1, LEFT    ) = 0100
rotatebits( 0100, 1, RIGHT ) = 0010
rotatebits( 0100, 2, LEFT    ) = 0001
....

O código está todo em inglês porque aqui não será o único lugar que vou publicar, aí não traduzi... :P

  



Versões atualizadas deste script

Versão 2 - Enviado por Enzo de Brito Ferber em 22/06/2017

Changelog: Novo algoritmo usando apenas bitwise para rotações.

Download rotate_bits.c


Esconder código-fonte

/* rotatebits.c 
 *
 * Enzo Ferber : <enzo@veloxmail.com.br>
 * sep 2010
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define LEFT        1
#define RIGHT       2

/* number of binary digits */
#define BINDIGS     8

/* friendly definitions */
#define BITMASK     0x80
#define LASTBIT     0x80
#define FIRSTBIT    0x01

/* printbin(n)
 * 
 * prints 'n' in binary form
 */
void printbin( int n )
{
     register int i;
     
     for( i = 0; i < BINDIGS; i++ )
          printf( "%c", (( n & (BITMASK >> i)) ? '1' : '0') );
     
     return ;
}

/* rotatebits( x, n, d )
 * 
 * x - number to rotate
 * n - n jumps
 * d - direction ( LEFT, RIGHT )
 */
int rotatebits( int x, int n, int d )
{
     register int i;
     unsigned bit;
     
     for( i = 0; i < n; i++ )
     {
          bit = ( d == LEFT ) ? LASTBIT : FIRSTBIT;
          
          /* saves the bit that will be lost in the shift */
          bit = x & bit;
          
          /* shifts the number */
          x = ( d == LEFT ) ? x << 1 : x >> 1;
          
          /* reset the lost bit in the other end of the number */
          x |= ( bit ? ((d == LEFT) ? FIRSTBIT : LASTBIT ) : 0x00 );
     }
     
     /* returns the new number rotated */
     return x;
}

/* just to fool around a little bit... */
int main( int argc, char *argv[] )
{
     register int i, j, x;
     
     if( argc < 2 )
     {
          printf( "Usage: %s <num1> (num2)...\n", argv[0] );
          printf( "[*] At least one number must be given...\n" );
          exit( 0 );
     }
     
     for( j = 1; j < argc; j++ )
     {
          for( i = 0; i <= BINDIGS; i++ )
          {
               x = rotatebits( atoi( argv[j] ), i , LEFT);
               printf( "left( %d, %d ) : ", atoi( argv[j] ), i );
               printbin( x ); printf( "\t\t" );
               
               x = rotatebits( atoi( argv[j] ), i , RIGHT);
               printf( "right( %d, %d ): ", atoi( argv[j] ), i );
               printbin( x );
               
               puts( "" );
          }
          puts( "\n" );
     }
     
     return 0;
}

Scripts recomendados

AA linux kernel modificado por minhe

Jogo Micro Breakout

Ordenar um lista estática sequencial básica (bubblesort)

Arquivos utilizados no artigo: "Desenvolvendo um plugin para o XMMS"

Script - Vetor


  

Comentários
[1] Comentário enviado por SamL em 19/09/2010 - 13:40h

Cara, muito bom o script.
Mas me diga, seu programa funciona caso a ordem dos bits seja big endian? Ou será preciso inverter os deslocamentos? (Sempre tive essa dúvida)

[2] Comentário enviado por vinipsmaker em 20/09/2010 - 23:06h

O código ficou realmente muito bom, +fav

[3] Comentário enviado por EnzoFerber em 21/09/2010 - 08:36h

Bom, a ordem dos bits está em big endian (BE)...

Por exemplo: 5f7a
BE: 5f - 7a
LE: 7a - 5f

Que é o padrão do programa, pois ele analisa os bits assim.
Se eu estiver errado me corrija, por que sempre me confundo com esses endian.... faze o quê?!

Ah, obrigado pelos elogios ^^


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts