Foro de elhacker.net

Programación => Programación C/C++ => Mensaje iniciado por: BlaineMonkey en 21 Junio 2011, 15:04 pm



Título: Convertir de Long a Binario
Publicado por: BlaineMonkey en 21 Junio 2011, 15:04 pm
Tengo una variable long y quiero convertir el número a binario, pero no sé cómo hacerlo.  Pongo un ejemplo de qué es lo que quiero, para ver si se os ocurre como podría hacerlo.
Ejemplo:
long valor = 5
int binData[8]={0,0,0,0,0,0,0,0};

Quiero guardar el 5 en binario en un array de 8 enteros el valor.

Ejemplo:
binData contendría el array siguiente: {0,0,0,0,0,1,0,1};

¿Cómo puedo hacerlo?


Título: Re: Convertir de Long a Binario
Publicado por: Ca0s en 21 Junio 2011, 15:28 pm
Haz la conversión a binario tal cual la harías con boli y papel...
Te pongo la conversión (la imprime al revés):

Código:
#include <stdio.h>
int main()
{
  long num=5;
  long res=0;
  long coc=0;
  while(num>=2)
  {
coc=num/2;
res=num%2;
printf("%i", res);
num=coc;
  }
  printf("%i\n", num);
  return 0;
}


Título: Re: Convertir de Long a Binario
Publicado por: BlackZeroX en 21 Junio 2011, 20:37 pm
.

Asi tambien se puede: <Aqui esta el codigo Corriendo en CodePad (http://codepad.org/QPVI9H1i)>

Código
  1.  
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <stdlib.h>
  5.  
  6. struct _byte_bits {
  7.    unsigned bit0:1;
  8.    unsigned bit1:1;
  9.    unsigned bit2:1;
  10.    unsigned bit3:1;
  11.    unsigned bit4:1;
  12.    unsigned bit5:1;
  13.    unsigned bit6:1;
  14.    unsigned bit7:1;
  15. };
  16.  
  17. int main()
  18. {
  19.    long        _long   = 78;
  20.    int         _i      = 0;
  21.    _byte_bits  _binary[sizeof(long)];
  22.  
  23.    memset( &_binary , 0 , sizeof(_byte_bits)*sizeof(long) );
  24.    memcpy( &_binary , &_long , sizeof(_byte_bits)*sizeof(long) );
  25.  
  26.    for ( _i=(sizeof(_byte_bits)-1) ; _i>=0 ; --_i ) {
  27.        fprintf( stdout , "%d" , _binary[_i].bit7 );
  28.        fprintf( stdout , "%d" , _binary[_i].bit6 );
  29.        fprintf( stdout , "%d" , _binary[_i].bit5 );
  30.        fprintf( stdout , "%d" , _binary[_i].bit4 );
  31.        fprintf( stdout , "%d" , _binary[_i].bit3 );
  32.        fprintf( stdout , "%d" , _binary[_i].bit2 );
  33.        fprintf( stdout , "%d" , _binary[_i].bit1 );
  34.        fprintf( stdout , "%d" , _binary[_i].bit0 );
  35.    }
  36.    return 0;
  37. }
  38.  

Dulces Lunas!¡.


Título: Re: Convertir de Long a Binario
Publicado por: Khronos14 en 21 Junio 2011, 22:06 pm
Los números long son de 4 bytes por lo tanto tienen 32 bits. Yo lo hice con un número de 8 bits, o sea, de tipo unsigned char.

Código
  1. #include <iostream>
  2.  
  3. int main(int argc, char * argv[])
  4. {
  5. unsigned char numBin[8], numero = 5;
  6. unsigned char aux = 0;
  7.  
  8. for (int i = 0; i < 8; i++)
  9. {
  10. aux = numero >> (7 - i);
  11. aux = aux << 7;
  12.  
  13. if (aux == 128)
  14. numBin[i] = 0x31; //Un 1
  15. else
  16. numBin[i] = 0x30; //Un 0
  17. std::cout << numBin[i];
  18. }
  19. std::cin.get();
  20. return 0;
  21. }
  22.  

Son puras matemáticas, se van desplazando los bits de derecha a izquierda para conseguir que quede 128, si es así significa que el bit actual es 1.

Saludos.


Título: Re: Convertir de Long a Binario
Publicado por: BlackZeroX en 21 Junio 2011, 23:18 pm
.
Con mascaras y con el dezplazamiento de bits ( los dos metodos mas rapidos ) puedes obtener el numero binario.

Aqui te dejo el codigo corriendo http://codepad.org/jfxvOYW5

Código
  1.  
  2. #include <stdio.h>
  3.  
  4. int main() {
  5.    unsigned char byte = 205;
  6.    fprintf( stdout , "%d" , (byte & 0x80)>>7 );
  7.    fprintf( stdout , "%d" , (byte & 0x40)>>6 );
  8.    fprintf( stdout , "%d" , (byte & 0x20)>>5 );
  9.    fprintf( stdout , "%d" , (byte & 0x10)>>4 );
  10.    fprintf( stdout , "%d" , (byte & 0x8)>>3 );
  11.    fprintf( stdout , "%d" , (byte & 0x4)>>2 );
  12.    fprintf( stdout , "%d" , (byte & 0x2)>>1 );
  13.    fprintf( stdout , "%d" , (byte & 0x1) );
  14.    return 0;
  15. }
  16.  
  17.  

P.D.: Los numeros Long dependen su longitud de bytes segun la arquitectura del PC es decir en una architectura x32 = 4 bytes y en una de x64 son 8 bytes... segun se la que le seguira en un futuro la de x128 sera de 16 bytes...

Dulces Lunas!¡.


Título: Re: Convertir de Long a Binario
Publicado por: Khronos14 en 22 Junio 2011, 14:01 pm
BlackZeroX no se de donde sacaste eso de los números long, pero yo tengo Win7 SP1 64 bits y haciendo un sizeof al tipo long me dice que son 4 bytes. Todo esto usando el Visual C++ 2010.

Saludos.


Título: Re: Convertir de Long a Binario
Publicado por: Queta en 22 Junio 2011, 14:13 pm
http://www.cplusplus.com/doc/tutorial/variables/ (http://www.cplusplus.com/doc/tutorial/variables/)

Y tema solucionado.


Título: Re: Convertir de Long a Binario
Publicado por: Akai en 22 Junio 2011, 14:20 pm
Khronos14 y Queta:

http://en.wikipedia.org/wiki/Long_integer

Fijaos en la diferencia según el sistema o el estándar que se use.

Por ejemplo, Linux kernel 2.6.39 x64 usando gcc 4.6:
Código
  1. #include <stdio.h>
  2.  
  3. int main(){
  4.  
  5. printf("%d %d %d\n",sizeof(int),sizeof(long),sizeof(long int));
  6.  
  7. return 0;
  8.  
  9. }
  10.  

resultado:
4 8 8


Título: Re: Convertir de Long a Binario
Publicado por: Queta en 22 Junio 2011, 14:41 pm
Obviamente, ya es lo que dije:

Citar
* The values of the columns Size and Range depend on the system the program is compiled for. The values shown above are those found on most 32-bit systems. But for other systems, the general specification is that int has the natural size suggested by the system architecture (one "word") and the four integer types char, short, int and long must each one be at least as large as the one preceding it, with char being always one byte in size. The same applies to the floating point types float, double and long double, where each one must provide at least as much precision as the preceding one.

http://www.cplusplus.com/doc/tutorial/variables/ (http://www.cplusplus.com/doc/tutorial/variables/)


Título: Re: Convertir de Long a Binario
Publicado por: Khronos14 en 22 Junio 2011, 15:13 pm
Vale hombre, no hagamos un flame de esto xD

Tan sólo me pareció raro, porque siempre pensé que el tipo long en Windows era de 4 bytes.

En mi Debian, con gcc version 4.4.5 (Debian 4.4.5-8) y Linux 2.6.32-5-686:

Código
  1. #include <stdio.h>
  2.  
  3. int main(){
  4.  
  5. printf("%d %d %d\n",sizeof(int),sizeof(long),sizeof(long int));
  6.  
  7. return 0;
  8.  
  9. }
  10.  

Me da esto:
4 4 4

Saludos.



Título: Re: Convertir de Long a Binario
Publicado por: BlackZeroX en 22 Junio 2011, 19:05 pm
.
TODO depende del sistema y del compilador, hasta donde yo se y he leido el tipo int se queda en 32 bits para evitar problemas, y se aumenta su capacidad con los modificadores.

http://codepad.org/yyM7CSdj

P.D.:trabajo sobre windows, algun dia vere como es linux... nada diferente por lo visto.

Dulces Lunas!¡.