2014-02-15 2 views
3

이진수를 10 진수로 변환하거나 그 반대로 변환 할 수있는 코드를 만듭니다. 10 진수를 2 진수로 변환하는 코드를 만들었지 만 10 진수로 2 진수를 구현하는 방법을 연습 할 수는 없습니다.2 진수에서 10 진수 Java 변환기

이진 소수점에 대한 나의 코드는 다음과 같습니다 :

import java.util.*; 
public class decimalToBinaryTest 
{ 
    public static void main (String [] args) 
    { 

     int n; 
     Scanner in = new Scanner(System.in); 

     System.out.println("Enter a positive interger"); 
     n=in.nextInt(); 

     if(n < 0) 
     { 
     System.out.println("Not a positive interger"); 
     } 

     else 
     { 
     System.out.print("Convert to binary is: "); 
     binaryform(n); 
     } 
    } 


    private static Object binaryform(int number) 
    { 

     int remainder; 

     if(number <= 1) 
     { 
     System.out.print(number); 
     return " "; 
     } 


     remainder= number % 2; 
     binaryform(number >> 1); 
     System.out.print(remainder); 
     { 
     return " "; 
     } 
    } 
} 

바이너리 코드 작업을 진수하는 방법에 대한 설명뿐만 아니라 도움이 될 것이다.

내가 가장 중요하지 않은 방법을 시도한 결과 digit*1 다음으로 *1*2 다음 *1*2*2이지만 작동시키지 못했습니다.

감사합니다. @korhner 배열 및 if 문과 함께 번호 시스템을 사용했습니다.

내 작업 코드 :

import java.util.*; 
public class binaryToDecimalConvertor 
{ 
    public static void main (String [] args) 
    { 
    int [] positionNumsArr= {1,2,4,8,16,32,64,128}; 
    int[] numberSplit = new int [8]; 
    Scanner scanNum = new Scanner(System.in); 
    int count1=0; 
    int decimalValue=0; 


    System.out.println("Please enter a positive binary number.(Only 1s and 0s)"); 
    int number = scanNum.nextInt(); 

    while (number > 0) 
    {  
     numberSplit[count1]=(number % 10); 
     if(numberSplit[count1]!=1 && numberSplit[count1] !=0) 
     { 
     System.out.println("Was not made of only \"1\" or \"0\" The program will now restart"); 
     main(null); 
     } 
     count1++; 
     number = number/10; 
    } 

    for(int count2 = 0;count2<8;count2++) 
    { 
    if(numberSplit[count2]==1) 
    { 
    decimalValue=decimalValue+positionNumsArr[count2]; 
    } 
    } 

    System.out.print(decimalValue); 

    } 
} 

답변

6

샘플 DOIT 선호하는 경우 :

00000100

0-1
을,2 - 0
1 - 4
0 - 8
0 - 16
0 - 64
- 0 - 128

비트

합계 값 1 = 4

좋음 32
0 운!

+1

1을 반환이다 . 질문은 숙제/운동 같아서 내 의견으로는 받아 들여진 대답이어야합니다. –

4
int decimal = Integer.parseInt("101101101010111", 2); 

또는 당신은 당신의 자기

double output=0; 

for(int i=0;i<str.length();i++){ 

    if(str.charAt(i)== '1') 
    output=output + Math.pow(2,str.length()-1-i); 

} 
+0

미안하지만 난 그 justdo 수 없습니다 뭘 메신저합니다.내가 루프와 물건 알고리즘을 필요 – userX

+0

할 maths.pow 무엇을 업데이트 대답 –

+0

을 확인? 숫자 – userX

0

원하십니까?

private double dec(String s, int i) { 
    if (s.length() == 1) return s.equals("1") ? Math.pow(2, i) : 0; 
    else return (s.equals("1") ? Math.pow(2, i) : 0) + dec(s.substring(0, s.length() - 1), i - 1); 
} 


dec("101011101",0); 
+0

답변을 게시 할 때 질문을 완전히 이해했는지 확인해야합니다.이를 달성하기 위해서는 주석을 사용해야합니다. –

+0

이것은 질문에 대한 대답을 제공하지 않습니다. 비평하거나 저자의 설명을 요청하려면 게시물 아래에 의견을 남겨 둡니다. –

+0

는 –

1

여기있는 프로그램이 있습니다.
int에 너무 큰 것이 아닌지 확인하십시오.

import java.util.Scanner; 


public class DecimalBinaryProgram { 

    public static void main(String[] args) { 

     Scanner in = new Scanner(System.in); 

     while (true){ 
      System.out.println("Enter integer in decimal form (or # to quit):"); 
      String s1 = in.nextLine(); 
      if ("#".equalsIgnoreCase(s1.trim())){ 
       break; 
      } 
      System.out.println(decimalToBinary(s1)); 
      System.out.println("Enter integer in binary form (or # to quit):"); 
      String s2 = in.nextLine(); 
      if ("#".equalsIgnoreCase(s2.trim())){ 
       break; 
      } 
      System.out.println(binaryToDecimal(s2)); 
     } 
    } 

    private static String decimalToBinary(String s){ 
     int n = Integer.parseInt(s, 10); 
     StringBuilder sb = new StringBuilder(); 

     if (n==0) return "0"; 
     int d = 0; 
     while (n > 0){ 
      d = n % 2; 
      n /= 2; 
      sb.append(d); 
     } 
     sb = sb.reverse(); 
     return sb.toString(); 
    } 

    private static String binaryToDecimal(String s){ 
     int degree = 1; 
     int n = 0; 
     for (int k=s.length()-1; k>=0; k--){ 
      n += degree * (s.charAt(k) - '0'); 
      degree *= 2; 
     } 
     return n + ""; 
    } 

} 
당신이 단지 수 binaryToDecimal이 방법 물론

:

private static String binaryToDecimal(String s){ 
    int n = Integer.parseInt(s, 2); 
    return n + ""; 
} 

하지만 난 당신이 명시 적으로 그렇게 할 수있는 방법을 설명하고 싶었다.

+0

감사를 @JakubKubrynski 감사합니다. 나는 이것이 어떻게 작동하는지 알게된다. 집에 도착하면 제대로 작동하도록 노력할 것입니다. – userX

0

이것은 10 진수 변환기의 이진 버전입니다. 나는 또한 많은 논평을 사용했다. 그냥 공유하고 싶습니다 가르쳐. 그것이 누군가에게 사용되기를 바랍니다.

import java.util.Scanner; 

public class BinaryToDecimal 
{ 
    public static void main(String args[]) 
    { 
     Scanner input = new Scanner(System.in); 
     System.out.println("Enter a binary number: "); 
     String binary = input.nextLine(); // store input from user 
     int[] powers = new int[16]; // contains powers of 2 
     int powersIndex = 0; // keep track of the index 
     int decimal = 0; // will contain decimals 
     boolean isCorrect = true; // flag if incorrect input 

     // populate the powers array with powers of 2 
     for(int i = 0; i < powers.length; i++) 
      powers[i] = (int) Math.pow(2, i); 

     for(int i = binary.length() - 1; i >= 0; i--) 
     { 
      // if 1 add to decimal to calculate 
      if(binary.charAt(i) == '1') 
       decimal = decimal + powers[powersIndex]; // calc the decimal 

      else if(binary.charAt(i) != '0' & binary.charAt(i) != '1') 
      { 
       isCorrect = false; // flag the wrong input 
       break; // break from loop due to wrong input 
      } // else if 

      // keeps track of which power we are on 
      powersIndex++; // counts from zero up to combat the loop counting down to zero 
     } // for 

     if(isCorrect) // print decimal output 
      System.out.println(binary + " converted to base 10 is: " + decimal); 
     else // print incorrect input message 
      System.out.println("Wrong input! It is binary... 0 and 1's like.....!"); 

    } // main 
} // BinaryToDecimal 
0

문자열과 int를 모두 허용하는 변환기를 작성했습니다.

public class Main { 

    public static void main(String[] args) { 

     int binInt = 10110111; 
     String binString = "10110111"; 
     BinaryConverter convertedInt = new BinaryConverter(binInt); 
     BinaryConverter convertedString = new BinaryConverter(binString); 

     System.out.println("Binary as an int, to decimal: " + convertedInt.getDecimal()); 
     System.out.println("Binary as a string, to decimal: " + convertedString.getDecimal()); 

    } 

} 

public class BinaryConverter { 

    private final int base = 2; 
    private int binaryInt; 
    private String binaryString; 
    private int convertedBinaryInt; 

    public BinaryConverter(int b) { 
     binaryInt = b; 
     convertedBinaryInt = Integer.parseInt(Integer.toString(binaryInt), base); 
    } 

    public BinaryConverter(String s) { 
     binaryString = s; 
     convertedBinaryInt = Integer.parseInt(binaryString, base); 
    } 

    public int getDecimal() { 
     return convertedBinaryInt; 
    } 

} 
0
public static void main(String[] args) 
{ 
    System.out.print("Enter a binary number: "); 
    Scanner input = new Scanner(System.in); 
    long num = input.nextLong(); 

    long reverseNum = 0; 
    int decimal = 0; 
    int i = 0; 

    while (num != 0) 
    { 
     reverseNum = reverseNum * 10; 
     reverseNum = num % 10; 
     decimal = (int) (reverseNum * Math.pow(2, i)) + decimal; 
     num = num/10; 
     i++; 
    } 
    System.out.println(decimal); 

} 
+0

또한이 코드의 용도와 OP가 도움이되는 이유에 대한 설명을 추가하십시오. –

관련 문제