logo

Programma konvertēšanai no decimālskaitļa uz bināru

Ievadot decimālskaitli, mums ir jāraksta programma, lai pārvērstu doto decimālskaitli par līdzvērtīgu bināro skaitli.

stīgu maiņa c

Piemēri No decimāldaļas līdz binārajai :

  Input : 7 Output : 111 Input : 10 Output : 1010 Input: 33 Output: 100001>
Ieteicamā prakse Decimāldaļas līdz binārajai Izmēģiniet to!

Brutālā spēka pieeja

Piemēram :
Ja decimālskaitlis ir 10.
1. darbība : Atlikums, kad 10 tiek dalīts ar 2, ir nulle. Tāpēc arr[0] = 0.
2. darbība : dala 10 ar 2. Jaunais skaitlis ir 10/2 = 5.
3. darbība : Atlikums, kad 5 tiek dalīts ar 2, ir 1. Tāpēc arr[1] = 1.
4. darbība : sadaliet 5 ar 2. Jaunais skaitlis ir 5/2 = 2.
5. darbība : Atlikums, kad 2 tiek dalīts ar 2, ir nulle. Tāpēc arr[2] = 0.
6. darbība : sadaliet 2 ar 2. Jaunais skaitlis ir 2/2 = 1.
7. darbība : Atlikums, ja 1 tiek dalīts ar 2, ir 1. Tāpēc arr[3] = 1.
8. darbība : dala 1 ar 2. Jaunais skaitlis ir 1/2 = 0.
9. darbība : Tā kā skaitlis kļūst par 0. Drukājiet masīvu apgrieztā secībā. Tāpēc līdzvērtīgs binārais skaitlis ir 1010.



Zemāk esošajā diagrammā parādīts piemērs decimālskaitļa 17 pārvēršanai par līdzvērtīgu bināro skaitli.

No decimāldaļas līdz binārajai




Zemāk ir iepriekš minētās idejas īstenošana.

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) { // atlikumu saglabāšana binārajā masīvā binaryNum[i] = n % 2;  n = n/2;  i++;  } // binārā masīva drukāšana apgrieztā secībā (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) { // atlikumu saglabāšana binārajā masīvā binaryNum[i] = n % 2;  n = n/2;  i++;  } // binārā masīva drukāšana apgrieztā secībā priekš (int j = i - 1; j>= 0; j--) printf('%d', binaryNum[j]); } // Draivera programma, lai pārbaudītu iepriekš minēto funkciju int main() { int n = 17;  decToBinary(n);  atgriezties 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) { // atlikumu saglabāšana binārajā masīvā binaryNum[i] = n % 2;  n = n/2;  i++;  } // binārā masīva drukāšana apgrieztā secībā priekš (int j = i - 1; j>= 0; j--) System.out.print(binaryNum[j]);  } // draivera programma public static void main(String[] args) { int n = 17;  decToBinary(n);  } } // Ieguldīja 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) { // atlikumu saglabāšana // binārajā masīvā binaryNum[i] = n % 2;  n = n/2;  i++;  } // binārā masīva drukāšana // apgrieztā secībā priekš (int j = i - 1; j>= 0; j--) Console.Write(binaryNum[j]);  } // Vadītāja kods public static void Main() { int n = 17;  decToBinary(n);  } } // Šo kodu nodrošina Sam007.>>Javascript0) { // atlikumu saglabāšana // binārajā masīvā $binaryNum[$i] = $n % 2; $n = (int)($n / 2); $i++; } // binārā masīva drukāšana // apgrieztā secībā priekš ($j = $i - 1; $j>= 0; $j--) echo $binaryNum[$j]; } // Vadītāja kods $n = 17; decToBinary($n); // Šo kodu nodrošina m_kit ?>>>Python3

Izvade
10001>

Laika sarežģītība: O(pieteikties) & palīgtelpa: O(1)

Mēs varam izmantot bitu operatorus, lai veiktu iepriekš minēto darbu. Ņemiet vērā, ka bitu operatori darbojas ātrāk nekā iepriekš izmantotie aritmētiskie operatori.

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;  ja (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; // pa labi nobīde if (k & 1) // palīdz mums uzzināt pirmā bita stāvokli printf('1');  else printf('0');  } } // draivera kods int main() { int n = 32;  decToBinary(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');  else System.out.print('0');  } } } class geek { // draivera kods public static void main(String[] args) { gfg g = new gfg();  int n = 32;  g.decToBinary(n);  } } // Šo kodu nodrošina 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 { // draivera kods public static int Main() { gfg g = new gfg();  int n = 32;  g.decToBinary(n);  atgriezties 0;  } }>
Javascript
>>PHP>
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='') # Draivera kods n = 32 decToBinary(n ) # Šo kodu nodrošina mits>

Izvade
00000000000000000000000000100000>

Laika sarežģītība: O(1)

cilpa atkārto konstanti (32) reižu skaitu katru reizi pat nelielam skaitam



Palīgtelpa: O(1)

Efektīva pieeja

Tā ir vēl viena efektīva pieeja decimāldaļas konvertēšanai uz bināru, izmantojot labo Shift(>>) un And(&) operatoru. Šeit mēs izmantosim tikai bināros operatorus, kas parasti ir ļoti ātri aprēķini.

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; // Pa labi Shift pa 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 ((skaitlis & 1) == 1) // 1 str += '1';  else // 0 str += '0';  skaits>>= 1; // Pa labi Shift par 1 } return str;  } // apgriezt virkni 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ārs no 59 ir: ');  reverse(DecimalToBinary(num));  } } // Šo kodu nodrošina 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 ((skaitlis & 1) == 1) // 1 str += '1';  else // 0 str += '0';  skaits>>= 1; // Pa labi Shift pa 1 } return str;  } // apgriezt virkni public static void reverse(String str) { for (int i = str.Length - 1; i>= 0; i--) Console.Write(str[i]);  } // Draivera kods public static void Main(string[] args) { int num = 59;  Console.Write('Binārs no 59 ir: ');  reverse(DecimalToBinary(num));  } } // šo kodu nodrošināja phasing17>
Javascript
>>Python3>= 1 atgriež strs # funkcija, lai apgrieztu virkni def reverse(strs): print(strs[::-1]) # Draivera koda numurs = 59 print('Binārs no num 59 ir:', end=' ') reverse(DecimalToBinary(num)) # Šo kodu nodrošina phasing17>

Izvade
Binary of num 59 is: 111011>

Laika sarežģītība: O(log n) & palīgtelpa: O(1)

Decimāldaļas konvertēšanu uz bināru var veikt arī, neizmantojot masīvus.

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
>>Python310001>

Laika sarežģītība: O(pieteikties) & palīgtelpa: O(1)

Ņemiet vērā, ka šī metode ir līdzīga tai, kurā mēs pārvēršam bināro uz decimālo, kā aprakstīts šajā pastu .
Ir vēl viena metode, kas jebkuru decimālo skaitli pārvērš binārajā formā. Ideja ir izmantot bitkopa .

Zemāk ir aprakstīta iepriekš minētās pieejas īstenošana.

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();    //Pirmā '1' sastopamības atrašana //lai noņemtu sākuma nulles.  const auto loc1 = s.find('1');    if(loc1 != string::npos) return s.substr(loc1);    atgriezt '0'; } //Driver Code int main() { int n = 17;    //Funkciju izsaukšana<< 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))>

Izvade
10001>

Laika sarežģītība: O(pieteikties) & palīgtelpa: O(1)

Cita pieeja

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>(skaitlis).to_string().substr(64 - n - 1); } // Šo kodu raksta 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>

Izvade
the binary number is : 1111>

Laika sarežģītība: O(pieteikties) & Palīgtelpa: O(1)