logo

Programa per a la conversió decimal a binària

Donat un nombre decimal com a entrada, hem d'escriure un programa per convertir el nombre decimal donat en un nombre binari equivalent.

Descarrega xvideoservicethief ubuntu 14.04

Exemples de De decimal a binari :

  Input : 7 Output : 111 Input : 10 Output : 1010 Input: 33 Output: 100001>
Pràctica recomanadaDecimal a binari Prova-ho!

Enfocament de força bruta

Per exemple :
Si el nombre decimal és 10.
Pas 1 : La resta quan es divideix 10 per 2 és zero. Per tant, arr[0] = 0.
Pas 2 : Dividiu 10 per 2. El nou nombre és 10/2 = 5.
Pas 3 : La resta quan es divideix 5 per 2 és 1. Per tant, arr[1] = 1.
Pas 4 : Divideix 5 per 2. El nou nombre és 5/2 = 2.
Pas 5 : La resta quan es divideix 2 per 2 és zero. Per tant, arr[2] = 0.
Pas 6 : Dividiu 2 per 2. El nou nombre és 2/2 = 1.
Pas 7 : La resta quan es divideix 1 per 2 és 1. Per tant, arr[3] = 1.
Pas 8 : Dividiu 1 per 2. El nou nombre és 1/2 = 0.
Pas 9 : Com que el nombre es converteix en = 0. Imprimeix la matriu en ordre invers. Per tant, el nombre binari equivalent és 1010.



El diagrama següent mostra un exemple de conversió del nombre decimal 17 a un nombre binari equivalent.

De decimal a binari




A continuació es mostra la implementació de la idea anterior.

C++
// C++ program to convert a decimal // number to binary number #include  using namespace std; // function to convert decimal to binary void decToBinary(int n) {  // array to store binary number  int binaryNum[32];  // counter for binary array  int i = 0;  while (n>0) { // emmagatzemar la resta a la matriu binària binaryNum[i] = n % 2;  n = n / 2;  i++;  } // imprimeix una matriu binària en ordre invers per a (int j = i - 1; j>= 0; j--) cout<< binaryNum[j]; } // Driver program to test above function int main() {  int n = 17;  decToBinary(n);  return 0; }>
C
// C Code to convert Decimal number into Binary #include  void decToBinary(int n) {  // array to store binary number  int binaryNum[32];    // counter for binary array  int i = 0;  while (n>0) { // emmagatzemar la resta a la matriu binària binaryNum[i] = n % 2;  n = n / 2;  i++;  } // imprimeix una matriu binària en ordre invers per a (int j = i - 1; j>= 0; j--) printf('%d', binaryNum[j]); } // Programa de controlador per provar la funció anterior int main() { int n = 17;  decToBinary(n);  retorn 0; }>>>Java0) { // emmagatzemar la resta a // matriu binària binaryNum[i] = n % 2;  n = n / 2;  i++;  } // imprimeix una matriu binària // en ordre invers per a (int j = i - 1; j>= 0; j--) Console.Write(binaryNum[j]);  } // Codi del controlador public static void Main() { int n = 17;  decToBinary(n);  } } // Aquest codi és aportat per Sam007.>>>Javascript 
 // PHP program to convert a decimal // number to binary number // function to convert // decimal to binary function decToBinary($n) { // array to store // binary number $binaryNum; // counter for binary array $i = 0; while ($n>0) { // emmagatzemar la resta // en una matriu binària $binaryNum[$i] = $n % 2; $n = (int)($n / 2); $i++; } // imprimint una matriu binària // en ordre invers per a ($j = $i - 1; $j>= 0; $j--) echo $núm binari[$j]; } // Codi del controlador $n = 17; decToBinary($n); // Aquest codi és aportat per m_kit ?>>
Python 3
# Python3 program to convert a  # decimal number to binary number # function to convert # decimal to binary def decToBinary(n): # array to store # binary number binaryNum = [0] * n # counter for binary array i = 0; while (n>0): # emmagatzemant la resta # a la matriu binària binaryNum[i] = n % 2 n = int(n / 2) i += 1 # imprimint la matriu binària # en ordre invers per a j en el rang (i - 1, -1, -1): print(binaryNum[j], end = '') # Codi del controlador n = 17 decToBinary(n) # Aquest codi és aportat per mits>

Sortida
10001>

Complexitat temporal: O (inici de sessió) & Espai auxiliar: O(1)

Podem utilitzar operadors bit a bit per fer el treball anterior. Tingueu en compte que els operadors per bit funcionen més ràpidament que els operadors aritmètics utilitzats anteriorment.

C++
// CPP program to Decimal to binary conversion // using bitwise operator // Size of an integer is assumed to be 32 bits #include  using namespace std; // Function that convert Decimal to binary void decToBinary(int n) {  // Size of an integer is assumed to be 32 bits  for (int i = 31; i>= 0; i--) { int k = n>> i;  si (k & 1) cout<< '1';  else  cout << '0';  } } // driver code int main() {  int n = 32;  decToBinary(n); }>
C
// C language to convert Decimal to binary number // using bitwise operator // Size of an integer is assumed to be 32 bits #include  // Function that convert Decimal to binary int decToBinary(int n) {  // Size of an integer is assumed to be 32 bits  for (int i = 31; i>= 0; i--) { int k = n>> i; // desplaçament a la dreta if (k & 1) // ens ajuda a conèixer l'estat del primer bit printf('1');  else printf('0');  } } // codi del controlador int main() { int n = 32;  decToBinary(n); }>>>Java>>C#>>Javascript= 0; i--) { var k = n>> i;  if ((k & 1)> 0) document.write('1');  else document.write('0');  } } // codi del controlador var n = 32;  decToBinary(n); // Aquest codi aportat per Princi Singh>
PHP
 // PHP program to Decimal to binary conversion // using bitwise operator // Size of an integer is assumed  // to be 32 bits // Function that convert Decimal to binary function decToBinary($n) { // Size of an integer is // assumed to be 32 bits for ( $i = 31; $i>= 0; $i--) { $k = $n>> $i; if ($k & 1) echo '1'; else echo '0'; } } // Codi del controlador $n = 32; decToBinary($n); // Aquest codi és aportat per aj_36 ?>>
Python 3
# Python3 program to Decimal # to binary conversion using # bitwise operator # Size of an integer is # assumed to be 32 bits # Function that convert # Decimal to binary def decToBinary(n): # Size of an integer is # assumed to be 32 bits for i in range(31, -1, -1): k = n>> i si (k & 1): print('1', final='') else: print('0', final='') # Codi del controlador n = 32 decToBinary(n ) # Aquest codi és aportat per mits>>>  
Sortida
00000000000000000000000000100000>

Complexitat temporal: O(1)

el bucle itera constant (32) nombre de vegades cada vegada, fins i tot per a un nombre petit



Espai auxiliar: O(1)

Enfocament eficient

És un altre enfocament eficient per convertir Decimal a binari mitjançant l'operador majúscules a la dreta (>>) i I (&). Aquí només utilitzarem operadors binaris que solen ser molt ràpids en el càlcul.

C++
#include  using namespace std; string DecimalToBinary(int num) {  string str;  while(num){  if(num & 1) // 1  str+='1';  else // 0  str+='0';  num>>=1; // Desplaçament a la dreta en 1 } return str; } void reverse(string str) { for(int i=str.size()-1 ; i>=0 ; i--) cout<< str[i];  } int main() {  int num = 59;  cout<< 'Binary of num 59 is: ';  reverse( DecimalToBinary(num) );  return 0; }>
Java
// Java program to implement the // above approach import java.io.*; class GFG  {  // the converts decimal to binary base  static String DecimalToBinary(int num)  {  String str = '';  while (num>0) { if ((núm i 1) == 1) // 1 str += '1';  else // 0 str += '0';  nombre>>= 1; // Desplaçament a la dreta en 1 } return str;  } // inverteix la cadena static void reverse(String str) { for (int i = str.length() - 1; i>= 0; i--) System.out.print(str.charAt(i));  } public static void main(String[] args) { int num = 59;  System.out.print('El binari del número 59 és: ');  reverse(DecimalToBinary(num));  } } // Aquest codi és aportat per phasing17>
C#
// C# program to implement the // above approach using System; public class GFG {    // this converts decimal to binary base  public static string DecimalToBinary(int num)  {  string str = '';  while (num>0) { if ((núm i 1) == 1) // 1 str += '1';  else // 0 str += '0';  nombre>>= 1; // Desplaçament a la dreta en 1 } return str;  } // inverteix la cadena public static void reverse(String str) { for (int i = str.Length - 1; i>= 0; i--) Console.Write(str[i]);  } // Codi del controlador public static void Main(string[] args) { int num = 59;  Console.Write('El binari del número 59 és: ');  reverse(DecimalToBinary(num));  } } // aquest codi ha estat aportat per phasing17>
Javascript
>
Python 3
# Python3 program to implement the above approach # function to convert the decimal number # to binary number def DecimalToBinary(num): strs = '' while num: # if (num & 1) = 1 if (num & 1): strs += '1' # if (num & 1) = 0 else: strs += '0' # right shift by 1 num>>= 1 return strs # funció per invertir la cadena def reverse(strs): print(strs[::-1]) # Codi del controlador num = 59 print('Binary of num 59 is:', end=' ') reverse(DecimalToBinary(num)) # Aquest codi és aportat per phasing17>>>  
Sortida La conversió de decimal a binària també es pot fer sense utilitzar matrius.

C++
// C++ implementation of the approach #include  #include  using namespace std; #define ull unsigned long long int // Function to return the binary // equivalent of decimal value N int decimalToBinary(int N) {  // To store the binary number  ull B_Number = 0;  int cnt = 0;  while (N != 0) {  int rem = N % 2;  ull c = pow(10, cnt);  B_Number += rem * c;  N /= 2;  // Count used to store exponent value  cnt++;  }  return B_Number; } // Driver code int main() {  int N = 17;  cout << decimalToBinary(N);  return 0; } // This code is contributed by Sania Kumari Gupta (kriSania804)>
C
// C implementation of the approach #include  #include  #define ull unsigned long long int // Function to return the binary // equivalent of decimal value N int decimalToBinary(int N) {  // To store the binary number  ull B_Number = 0;  int cnt = 0;  while (N != 0) {  int rem = N % 2;  ull c = pow(10, cnt);  B_Number += rem * c;  N /= 2;  // Count used to store exponent value  cnt++;  }  return B_Number; } // Driver code int main() {  int N = 17;  printf('%u', decimalToBinary(N));  return 0; } // This code is contributed by Sania Kumari Gupta (kriSania804)>
Java
// Java implementation of the approach  import java.io.*; class GFG  { // Function to return the binary  // equivalent of decimal value N  static int decimalToBinary(int N)  {   // To store the binary number   int B_Number = 0;   int cnt = 0;   while (N != 0)  {   int rem = N % 2;   double c = Math.pow(10, cnt);   B_Number += rem * c;   N /= 2;   // Count used to store exponent value   cnt++;   }   return B_Number;  }  // Driver code  public static void main (String[] args) {    int N = 17;   System.out.println (decimalToBinary(N));  } } // This code is contributed by ajit.>
C#
// C# implementation of the approach using System; class GFG {   // Function to return the binary  // equivalent of decimal value N  static int decimalToBinary(int N)  {   // To store the binary number   int B_Number = 0;   int cnt = 0;   while (N != 0)  {   int rem = N % 2;   int c = (int)Math.Pow(10, cnt);   B_Number += rem * c;   N /= 2;   // Count used to store exponent value   cnt++;   }   return B_Number;  }  // Driver code  static public void Main () {  int N = 17;   Console.Write(decimalToBinary(N));  } } // This code is contributed by Tushil.>
Javascript
>
Python 3
# Python3 implementation of the approach  # Function to return the binary  # equivalent of decimal value N  def decimalToBinary(N): # To store the binary number  B_Number = 0 cnt = 0 while (N != 0): rem = N % 2 c = pow(10, cnt) B_Number += rem * c N //= 2 # Count used to store exponent value  cnt += 1 return B_Number # Driver code  N = 17 print(decimalToBinary(N)) # This code is contributed by  # SHUBHAMSINGH10>

Sortida Tingueu en compte que aquest mètode és similar al que convertim Binari a Decimal com s'explica a continuació publicació .
Hi ha un altre mètode que converteix qualsevol nombre decimal a la seva forma binària. La idea és utilitzar bitset .

A continuació es mostra la implementació de l'enfocament anterior.

C++
//C++ program to convert a decimal number //to its binary form. //including header file #include  using namespace std; //Function to convert a decimal number //to its binary form string decimalToBinary(int n) {  //finding the binary form of the number and   //converting it to string.   string s = bitset<64>(n).to_string();    //Trobant la primera ocurrència de '1' //per eliminar els zeros inicials.  const auto loc1 = s.find('1');    if(loc1 != string::npos) return s.substr(loc1);    retornar '0'; } //Codi del controlador int main() { int n = 17;    //Crida de funció cout<< decimalToBinary(n);  return 0; } //This code is contributed by yashbeersingh42>
Java
// Java program to convert a decimal number to its binary // form import java.util.*; class DecimalToBinary {  // Function to convert a decimal number to its binary  // form  public static String decimalToBinary(int n)  {  // Finding the binary form of the number and  // converting it to a string  String s = Integer.toBinaryString(n);  // Finding the first occurrence of '1' to strip off  // the leading zeroes  int loc1 = s.indexOf('1');  if (loc1 != -1) {  return s.substring(loc1);  }  return '0';  }  // Driver code  public static void main(String[] args)  {  int n = 17;  // Function call  System.out.println(decimalToBinary(n));  } } // This code is contributed by phasing17>
C#
// C# program to convert a decimal number // to its binary form. using System; class HelloWorld {  // Function to convert a decimal number  // to its binary form  public static String decimalToBinary(int n)  {  // finding the binary form of the number and   //converting it to string.   String s = Convert.ToString(n, 2);  return s;  }  static void Main() {  int n = 17;  //Function call  Console.WriteLine(decimalToBinary(n));  } } // The code is contributed by Nidhi goel.>
Javascript
// Javascript program to convert a decimal number // to its binary form. // Function to convert a decimal number // to its binary form function decimalToBinary( n) {  // finding the binary form of the number and   // converting it to string.   const s = n.toString(2);    return s; } // Driver Code let n = 17; // Function call console.log(decimalToBinary(n));  // This code is contributed by imruhrbf8.>
Python 3
# Python program to convert a decimal number # to its binary form. # Function to convert a decimal number # to its binary form def decimalToBinary( n): # finding the binary form of the number and  # converting it to string.  s = bin(n)[2:] # Finding the first occurrence of '1' # to strip off the leading zeroes. # const auto loc1 = s.find('1') loc1 = s[s.index('1'):] return loc1 return '0' # Driver Code n = 17 # Function call print(decimalToBinary(n))>

Sortida
10001>

Complexitat temporal: O (inici de sessió) & Espai auxiliar: O(1)

Un altre Enfocament

C++
// C++ program to convert Decimal to Binary Number #include  using namespace std; int main() {  // input number  int number = 15;  int n = (int)(log2(number));    // binary output  // using the inbuilt function  cout << 'the binary number is : '  << bitset<64>(número).to_string().substr(64 - n - 1); } // Aquest codi s'escriu mitjançant phasing17>
Java
//To convert Decimal to Binary Number// import java.util.*;  public class Main{  public static void main(String [] args){  //input//  int number =15;    //output//  System.out.println('the binary number is : '+ Integer.toString(number,2));    //This code is written by ZEESHAN AHMAD//  }  }>
C#
// To convert Decimal to Binary Number// using System;  class GFG{  public static void Main(){  // input//  int number =15;    //output//  Console.WriteLine('the binary number is : '+ Convert.ToString(number, 2));  }  } // This code is contributed by code_hunt.>
Javascript
// JavaScript program to convert Decimal to Binary Number // input number var number = 15; // binary output // using the inbuilt function console.log('the binary number is :', number.toString(2)); // This code is written by phasing17>
Python 3
# Python3 program to convert Decimal to Binary Number # input number number = 15 # binary output # using the inbuilt function print('the binary number is :', bin(number)[2::]) # This code is written by phasing17>

Sortida
the binary number is : 1111>

Complexitat temporal: O (inici de sessió) & Espai auxiliar: O(1)