十进制到二进制转换的Java程序

给定一个十进制数作为输入,我们需要编写一个程序,将给定的十进制数转换为等效的二进制数。

null

例如:

Input : 7
Output : 111
s
Input : 10
Output : 1010

Input: 33
Output: 100001

二进制到十进制转换是将二进制中给定的数字转换为十进制中的等效数字。数字系统是以某种方式表示数字的一种格式。

二进制数系统– 二进制数系统在计算机和电子系统中用来表示数据,它只由0和1两个数字组成。

十进制 十进制是世界上最常用的数字系统,人们很容易理解。它由0到9的数字组成。

方法

在Java中,有许多方法可以将给定的十进制数转换为等效的二进制数。下面列出了其中一些。

  • 使用数组
  • 使用位运算符
  • 使用数学。pow()函数(不使用数组)

1.使用数组

算法 :

  1. 将数字除以2后的余数存储在数组中。
  2. 把这个数字除以2
  3. 重复上述两个步骤,直到数字大于零。
  4. 现在按相反顺序打印阵列。

下图显示了将十进制数17转换为等效二进制数的示例。

图片[1]-十进制到二进制转换的Java程序-yiteyi-C++库

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 [ 1000 ];
// counter for binary array
int i = 0 ;
while (n > 0 )
{
// storing remainder in binary array
binaryNum[i] = n % 2 ;
n = n / 2 ;
i++;
}
// printing binary array in reverse order
for ( int j = i - 1 ; j >= 0 ; j--)
System.out.print(binaryNum[j]);
}
// driver program
public static void main (String[] args)
{
int n = 17 ;
System.out.println( "Decimal - " + n);
System.out.print( "Binary - " );
decToBinary(n);
}
}
// Contributed by Pramod Kumar


输出

Decimal - 17
Binary - 10001

2.使用位运算符

我们可以使用位运算符来完成上述工作。

注—— 位运算符比上面使用的算术运算符工作得更快。

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 {
// driver code
public static void main(String[] args)
{
gfg g = new gfg();
int n = 32 ;
System.out.println( "Decimal - " + n);
System.out.print( "Binary - " );
g.decToBinary(n);
}
}
// This code is contributed by mits


输出

Decimal - 32
Binary - 00000000000000000000000000100000

3.运用数学。pow()方法(不使用数组)

十进制到二进制的转换也可以在不使用数组的情况下完成。

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( "Decimal - " + N);
System.out.print( "Binary - " );
System.out.println(decimalToBinary(N));
}
}
// This code is contributed by ajit.


输出

Decimal - 17
Binary - 10001

请参阅完整的文章 十进制到二进制转换程序 更多细节!

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享