programing

Java에서 int를 이진 문자열 표현으로 변환하시겠습니까?

bestcode 2022. 8. 25. 23:55
반응형

Java에서 int를 이진 문자열 표현으로 변환하시겠습니까?

Java에서 int를 바이너리 문자열 표현으로 변환하는 가장 좋은 방법(이상적으로 가장 간단한 방법)은 무엇입니까?

예를 들어 int가 156이라고 합니다.이 바이너리 문자열은 "10011100"이 됩니다.

Integer.toBinaryString(int i)

java.lang도 있습니다.Integer.toString(int i, int base) 메서드입니다.이 메서드는 사용하시는 코드가 2(이진수) 이외의 베이스를 처리하는 경우에 적합합니다.이 메서드는 정수 i를 부호 없이 나타낼 뿐이며, 음수인 경우 전면에 음수 기호가 부착됩니다.2의 보수는 사용하지 않을 것이다.

public static string intToBinary(int n)
{
    String s = "";
    while (n > 0)
    {
        s =  ( (n % 2 ) == 0 ? "0" : "1") +s;
        n = n / 2;
    }
    return s;
}

한 가지 더 - java.lang을 사용하여 번째 인수의 문자열 표현을 가져올 수 있는 정수i에서radix (Octal - 8, Hex - 16, Binary - 2)두 번째 인수에 의해 지정됩니다.

 Integer.toString(i, radix)

예_

private void getStrtingRadix() {
        // TODO Auto-generated method stub
         /* returns the string representation of the 
          unsigned integer in concern radix*/
         System.out.println("Binary eqivalent of 100 = " + Integer.toString(100, 2));
         System.out.println("Octal eqivalent of 100 = " + Integer.toString(100, 8));
         System.out.println("Decimal eqivalent of 100 = " + Integer.toString(100, 10));
         System.out.println("Hexadecimal eqivalent of 100 = " + Integer.toString(100, 16));
    }

출력_

Binary eqivalent of 100 = 1100100
Octal eqivalent of 100 = 144
Decimal eqivalent of 100 = 100
Hexadecimal eqivalent of 100 = 64
public class Main  {

   public static String toBinary(int n, int l ) throws Exception {
       double pow =  Math.pow(2, l);
       StringBuilder binary = new StringBuilder();
        if ( pow < n ) {
            throw new Exception("The length must be big from number ");
        }
       int shift = l- 1;
       for (; shift >= 0 ; shift--) {
           int bit = (n >> shift) & 1;
           if (bit == 1) {
               binary.append("1");
           } else {
               binary.append("0");
           }
       }
       return binary.toString();
   }

    public static void main(String[] args) throws Exception {
        System.out.println(" binary = " + toBinary(7, 4));
        System.out.println(" binary = " + Integer.toString(7,2));
    }
}

이건 내가 몇 분 전에 그냥 빈둥빈둥 쓴 거야.도움이 됐으면 좋겠다!

public class Main {

public static void main(String[] args) {

    ArrayList<Integer> powers = new ArrayList<Integer>();
    ArrayList<Integer> binaryStore = new ArrayList<Integer>();

    powers.add(128);
    powers.add(64);
    powers.add(32);
    powers.add(16);
    powers.add(8);
    powers.add(4);
    powers.add(2);
    powers.add(1);

    Scanner sc = new Scanner(System.in);
    System.out.println("Welcome to Paden9000 binary converter. Please enter an integer you wish to convert: ");
    int input = sc.nextInt();
    int printableInput = input;

    for (int i : powers) {
        if (input < i) {
            binaryStore.add(0);     
        } else {
            input = input - i;
            binaryStore.add(1);             
        }           
    }

    String newString= binaryStore.toString();
    String finalOutput = newString.replace("[", "")
            .replace(" ", "")
            .replace("]", "")
            .replace(",", "");

    System.out.println("Integer value: " + printableInput + "\nBinary value: " + finalOutput);
    sc.close();
}   

}

정수를 이진수로 변환:

import java.util.Scanner;

public class IntegerToBinary {

    public static void main(String[] args) {

        Scanner input = new Scanner( System.in );

        System.out.println("Enter Integer: ");
        String integerString =input.nextLine();

        System.out.println("Binary Number: "+Integer.toBinaryString(Integer.parseInt(integerString)));
    }

}

출력:

정수 입력:

10

이진수: 1010

내장 기능 사용:

String binaryNum = Integer.toBinaryString(int num);

내장 함수를 사용하여 int를 바이너리로 변환하지 않을 경우 다음과 같이 할 수도 있습니다.

import java.util.*;
public class IntToBinary {
    public static void main(String[] args) {
        Scanner d = new Scanner(System.in);
        int n;
        n = d.nextInt();
        StringBuilder sb = new StringBuilder();
        while(n > 0){
        int r = n%2;
        sb.append(r);
        n = n/2;
        }
        System.out.println(sb.reverse());        
    }
}

가장 간단한 방법은 숫자가 홀수인지 확인하는 것입니다.정의상 가장 오른쪽의 이진수는 "1"(2^0)이 됩니다.이 값을 확인한 후 숫자를 오른쪽으로 비트 이동시키고 재귀로 동일한 값을 확인합니다.

@Test
public void shouldPrintBinary() {
    StringBuilder sb = new StringBuilder();
    convert(1234, sb);
}

private void convert(int n, StringBuilder sb) {

    if (n > 0) {
        sb.append(n % 2);
        convert(n >> 1, sb);
    } else {
        System.out.println(sb.reverse().toString());
    }
}

여기 내 방법이 있다. 바이트 수가 고정되어 있다는 것은 약간 납득이 간다.

private void printByte(int value) {
String currentBinary = Integer.toBinaryString(256 + value);
System.out.println(currentBinary.substring(currentBinary.length() - 8));
}

public int binaryToInteger(String binary) {
char[] numbers = binary.toCharArray();
int result = 0;
for(int i=numbers.length - 1; i>=0; i--)
  if(numbers[i]=='1')
    result += Math.pow(2, (numbers.length-i - 1));
return result;
}

비트 시프트를 사용하는 것이 조금 더 빠릅니다.

public static String convertDecimalToBinary(int N) {

    StringBuilder binary = new StringBuilder(32);

    while (N > 0 ) {
        binary.append( N % 2 );
        N >>= 1;
     }

    return binary.reverse().toString();

}

이것은 의사 코드로 다음과 같이 나타낼 수 있습니다.

while(n > 0):
    remainder = n%2;
    n = n/2;
    Insert remainder to front of a list or push onto a stack

Print list or stack

반드시 Integer.toBinaryString()사용해야 하지만 어떤 이유로든 원하는 경우 다음과 같이 하십시오.

// Like Integer.toBinaryString, but always returns 32 chars
public static String asBitString(int value) {
  final char[] buf = new char[32];
  for (int i = 31; i >= 0; i--) {
    buf[31 - i] = ((1 << i) & value) == 0 ? '0' : '1';
  }
  return new String(buf);
}

int 값이 15일 경우 다음과 같이 바이너리로 변환할 수 있습니다.

int x = 15;

Integer.toBinaryString(x);

binary 값이 있으면 다음과 같이 int 값으로 변환할 수 있습니다.

String binaryValue = "1010";

Integer.parseInt(binaryValue, 2);

이것은 다음과 같은 것으로는 매우 간단할 것입니다.

public static String toBinary(int number){
    StringBuilder sb = new StringBuilder();

    if(number == 0)
        return "0";
    while(number>=1){
        sb.append(number%2);
        number = number / 2;
    }

    return sb.reverse().toString();

}
public class BinaryConverter {

    public static String binaryConverter(int number) {
        String binary = "";
        if (number == 1){
            binary = "1";
            return binary;
        }
        if (number == 0){
            binary = "0";
            return binary;
        }
        if (number > 1) {
            String i = Integer.toString(number % 2);

            binary = binary + i;
            binaryConverter(number/2);
        }
        return binary;
    }
}

while loop을 사용하여 int를 바이너리로 변환할 수도 있습니다.이것처럼.

import java.util.Scanner;

public class IntegerToBinary
{
   public static void main(String[] args)
   {
      int num;
      String str = "";
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter the a number : ");
      num = sc.nextInt();
      while(num > 0)
      {
         int y = num % 2;
         str = y + str;
         num = num / 2;
      }
      System.out.println("The binary conversion is : " + str);
      sc.close();
   }
}

소스 및 참조 - Java 예제에서 int를 이진수로 변환합니다.

정확히 8비트를 만들기 위해 @sandeep-saini의 답변에 조금 추가했습니다.

public static String intToBinary(int number){
        StringBuilder sb = new StringBuilder();

        if(number == 0)
            return "0";
        while(number>=1){
            sb.append(number%2);
            number = number / 2;
        }
        while (sb.length() < 8){
            sb.append("0");
        }

        return sb.reverse().toString();

    }

자, 이제 다음 입력에 대해서1의 출력을 얻을 수 있습니다.00000001

public static String intToBinaryString(int n) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 32 && n != 0; i++) {
        sb.append((n&1) == 1 ? "1" : "0");
        n >>= 1;
    }
    return sb.reverse().toString();
}

해서 사용할 수 .n%2 해서 '어디서'를 써야 요.n&1.

내 2센트:

public class Integer2Binary {
    public static void main(String[] args) {
        final int integer12 = 12;
        System.out.println(integer12 + " -> " + integer2Binary(integer12));
        // 12 -> 00000000000000000000000000001100
    }

    private static String integer2Binary(int n) {
        return new StringBuilder(Integer.toBinaryString(n))
            .insert(0, "0".repeat(Integer.numberOfLeadingZeros(n)))
            .toString();
    }
}

언급URL : https://stackoverflow.com/questions/2406432/converting-an-int-to-a-binary-string-representation-in-java

반응형