logo

Program for decimal til binær konvertering

Givet et decimaltal som input, skal vi skrive et program til at konvertere det givne decimaltal til et tilsvarende binært tal.

java string format langt

Eksempler på Decimal til binær :

  Input : 7 Output : 111 Input : 10 Output : 1010 Input: 33 Output: 100001>
Anbefalet praksisDecimal til binærPrøv det!

Brute force Approach

For eksempel :
Hvis decimaltallet er 10.
Trin 1 : Resten, når 10 divideres med 2, er nul. Derfor er arr[0] = 0.
Trin 2 : Divider 10 med 2. Nyt tal er 10/2 = 5.
Trin 3 : Resten, når 5 divideres med 2, er 1. Derfor er arr[1] = 1.
Trin 4 : Divider 5 med 2. Nyt tal er 5/2 = 2.
Trin 5 : Resten, når 2 divideres med 2, er nul. Derfor er arr[2] = 0.
Trin 6 : Divider 2 med 2. Nyt tal er 2/2 = 1.
Trin 7 : Resten, når 1 divideres med 2, er 1. Derfor er arr[3] = 1.
Trin 8 : Divider 1 med 2. Nyt tal er 1/2 = 0.
Trin 9 : Da tal bliver = 0. Udskriv arrayet i omvendt rækkefølge. Derfor er det tilsvarende binære tal 1010.



Nedenstående diagram viser et eksempel på konvertering af decimaltallet 17 til et tilsvarende binært tal.

Decimal til binær




Nedenfor er implementeringen af ​​ovenstående idé.

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) { // lagring af rest i binært array binærtNum[i] = n % 2;  n = n/2;  i++;  } // udskrivning af binært array i omvendt rækkefølge for (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) { // lagring af rest i binært array binærtNum[i] = n % 2;  n = n/2;  i++;  } // udskrivning af binært array i omvendt rækkefølge for (int j = i - 1; j>= 0; j--) printf('%d', binærtNum[j]); } // Driverprogram til at teste ovenstående funktion int main() { int n = 17;  decToBinær(n);  retur 0; }>
Java
// Java program to convert a decimal // number to binary number import java.io.*; class GFG {  // function to convert decimal to binary  static void decToBinary(int n)  {  // array to store binary number  int[] binaryNum = new int[32];  // counter for binary array  int i = 0;  while (n>0) { // lagring af rest i binært array binærtNum[i] = n % 2;  n = n/2;  i++;  } // udskrivning af binært array i omvendt rækkefølge for (int j = i - 1; j>= 0; j--) System.out.print(binærtNum[j]);  } // driverprogram public static void main(String[] args) { int n = 17;  decToBinær(n);  } } // Bidraget af Pramod Kumar>
C#
// C# program to convert a decimal // number to binary number using System; public class GFG {  // function to convert decimal  // to binary  static void decToBinary(int n)  {  // array to store binary number  int[] binaryNum = new int[32];  // counter for binary array  int i = 0;  while (n>0) { // lagring af rest i // binært array binærtNum[i] = n % 2;  n = n/2;  i++;  } // udskrivning af binært array // i omvendt rækkefølge for (int j = i - 1; j>= 0; j--) Console.Write(binaryNum[j]);  } // Driver Code public static void Main() { int n = 17;  decToBinær(n);  } } // Denne kode er bidraget af Sam007.>
Javascript
>
PHP
 // 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) { // lagring af rest // i binært array $binaryNum[$i] = $n % 2; $n = (int)($n / 2); $i++; } // udskrivning af binært array // i omvendt rækkefølge for ($j = $i - 1; $j>= 0; $j--) echo $binaryNum[$j]; } // Driverkode $n = 17; decToBinary($n); // Denne kode er bidraget af m_kit ?>>
Python3
# 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): # lagrer resten # i binært array binærtNum[i] = n % 2 n = int(n / 2) i += 1 # udskriver binært array # i omvendt rækkefølge for j i område(i - 1, -1, -1): print(binaryNum[j], end = '') # Driverkode n = 17 decToBinary(n) # Denne kode er bidraget af mits>

Produktion
10001>

Tidskompleksitet: O(logn) & Hjælpeplads: O(1)

Vi kan bruge bitvise operatorer til at udføre ovenstående job. Bemærk, at bitvise operatorer virker hurtigere end aritmetiske operatorer brugt ovenfor.

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;  hvis (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; // højreskift if (k & 1) // hjælper os med at kende tilstanden af ​​første bit printf('1');  andet printf('0');  } } // driverkode int main() { int n = 32;  decToBinær(n); }>
Java
// Java program to Decimal to binary conversion // using bitwise operator // Size of an integer is assumed to be 32 bits class gfg {  // Function that convert Decimal to binary  public 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;  if ((k & 1)> 0) System.out.print('1');  andet System.out.print('0');  } } } class geek { // driver code public static void main(String[] args) { gfg g = new gfg();  int n = 32;  g.decToBinary(n);  } } // Denne kode er bidraget af mits>
C#
// C# program to Decimal to binary conversion // using bitwise operator // Size of an integer is assumed to be 32 bits using System; class gfg {  // Function that convert Decimal to binary  public 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;  if ((k & 1)> 0) Console.Write('1');  else Console.Write('0');  } } } class geek { // driver code public static int Main() { gfg g = new gfg();  int n = 32;  g.decToBinary(n);  retur 0;  } }>
Javascript
>
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) ekko '1'; andet ekko '0'; } } // Driverkode $n = 32; decToBinary($n); // Denne kode er bidraget af aj_36 ?>>
Python3
# 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 if (k & 1): print('1', end='') else: print('0', end='') # Driverkode n = 32 decToBinary(n ) # Denne kode er bidraget af mits>

Produktion
00000000000000000000000000100000>

Tidskompleksitet: O(1)

loop iterates konstant(32) antal gange hver gang selv for et lille antal



Hjælpeplads: O(1)

Effektiv tilgang

Det er en anden effektiv tilgang til at konvertere decimal til binær ved hjælp af den rigtige shift(>>) og And(&) operator. Her bruger vi kun binære operatører, som normalt er meget hurtige i beregningen.

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; // Højre Skift med 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 ((antal & 1) == 1) // 1 str += '1';  andet // 0 str += '0';  antal>>= 1; // Højre Skift med 1 } return str;  } // reverse the string 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('Binær af nummer 59 er: ');  reverse(DecimalToBinary(antal));  } } // Denne kode er bidraget af 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 ((antal & 1) == 1) // 1 str += '1';  andet // 0 str += '0';  antal>>= 1; // Højre Skift med 1 } return str;  } // reverse the string public static void reverse(String str) { for (int i = str.Length - 1; i>= 0; i--) Console.Write(str[i]);  } // Driver Code public static void Main(string[] args) { int num = 59;  Console.Write('Binær af nummer 59 er: ');  reverse(DecimalToBinary(antal));  } } // denne kode blev bidraget af phasing17>
Javascript
>
Python3
# 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 returner strs # funktion for at vende strengen def reverse(strs): print(strs[::-1]) # Driver Kode num = 59 print('Binær af num 59 er:', end=' ') reverse(DecimalToBinary(num)) # Denne kode er bidraget af phasing17>

Produktion
Binary of num 59 is: 111011>

Tidskompleksitet: O(log n) & Hjælpeplads: O(1)

Decimal til binær konvertering kan også udføres uden brug af arrays.

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
>
Python3
# 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>

Produktion
10001>

Tidskompleksitet: O(logn) & Hjælpeplads: O(1)

Bemærk, at denne metode ligner den, hvor vi konverterer binær til decimal som diskuteret i dette stolpe .
Der er endnu en metode, der konverterer ethvert decimaltal til dets binære form. Ideen er at bruge bitsæt .

Nedenfor er implementeringen af ​​ovenstående tilgang.

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).til_streng();    //Find den første forekomst af '1' //for at fjerne de foranstillede nuller.  const auto loc1 = s.find('1');    if(loc1 != streng::npos) returner s.substr(loc1);    returner '0'; } //Driverkode int main() { int n = 17;    //Funktionskald 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.>
Python3
# 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))>

Produktion
10001>

Tidskompleksitet: O(logn) & Hjælpeplads: O(1)

En anden tilgang

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>(nummer).to_string().substr(64 - n - 1); } // Denne kode er skrevet af 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>
Python3
# 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>

Produktion
the binary number is : 1111>

Tidskompleksitet: O(logn) & Hjælpeplads: O(1)