Java에서 이진 형식으로 정수 인쇄


277

숫자가 있고 이진수로 인쇄하고 싶습니다. 알고리즘을 작성하여하고 싶지 않습니다 .Java에 내장 기능이 있습니까?

답변:


434

"내장"을 의미한다고 가정합니다.

int x = 100;
System.out.println(Integer.toBinaryString(x));

정수 설명서를 참조하십시오 .

( Long유사한 방법 BigInteger이 있고 기수를 지정할 수있는 인스턴스 방법이 있습니다.)


2
이것은 최고의 0을 생략합니다
Abu Ruqaiyah

1
@AbuRuqaiyah : OP는 선행 0을 언급하지 않았으며 한 가지에 대해 얼마나 많은 숫자를 기대해야하는지 알아야합니다.
Jon Skeet

@AbuRuqaiyah 선행 0을 원하면 System.out.printf ()를 사용하여 많은 제어를 할 수 있습니다.
NomadMaker

246

여기서는 바이너리 나 다른 형식에만 의존 할 필요가 없습니다. 융통성있는 내장 함수를 사용할 수 있습니다. 프로그램에서 원하는 형식을 인쇄합니다. Integer.toString (int, representation);

Integer.toString(100,8) // prints 144 --octal representation

Integer.toString(100,2) // prints 1100100 --binary representation

Integer.toString(100,16) //prints 64 --Hex representation

음수, 양수, 큰 숫자, 작은 숫자로 테스트
Tertium

8
toBinaryString2의 보수 출력을 사용 toString하고 지정된 밑수를 가리고 음수 부호를 앞에 둡니다.toString(-8, 2) == "-1000"
Joe


21

물건을 멋지게 인쇄하고 n 비트마다 비트를 분리하는 것이 필요했습니다. 즉, 앞에 0을 표시하고 다음과 같이 표시하십시오.

n = 5463
output = 0000 0000 0000 0000 0001 0101 0101 0111

내가 쓴 것은 다음과 같습니다.

/**
 * Converts an integer to a 32-bit binary string
 * @param number
 *      The number to convert
 * @param groupSize
 *      The number of bits in a group
 * @return
 *      The 32-bit long bit string
 */
public static String intToString(int number, int groupSize) {
    StringBuilder result = new StringBuilder();

    for(int i = 31; i >= 0 ; i--) {
        int mask = 1 << i;
        result.append((number & mask) != 0 ? "1" : "0");

        if (i % groupSize == 0)
            result.append(" ");
    }
    result.replace(result.length() - 1, result.length(), "");

    return result.toString();
}

다음과 같이 호출하십시오.

public static void main(String[] args) {
    System.out.println(intToString(5463, 4));
}

result.replace(result.length() - 1, result.length(), "");필요한가요? 우리가 지나갈 때 int이미 32 비트입니다. 마지막 두 번째 줄에서 무엇을 교체하고 있습니까?
Parth

1
@Parth 각 단계에서 문자열 끝에 공백 문자 ( "")를 추가합니다. 언급 한 줄은 마지막으로 추가 된 공백 문자를 제거합니다. 기본적으로 String클래스의 trim함수를 호출 하여 동일한 효과를 얻을 수 있습니다.
Maghoumi

숫자에 0x100000000을 더한 다음 길게 변환 한 다음 선행 1을 버림으로써이 작업을 훨씬 더 간단하고 효율적으로 수행 할 수 있습니다.
Lorqui of

7

오래된 학교:

    int value = 28;
    for(int i = 1, j = 0; i < 256; i = i << 1, j++)
        System.out.println(j + " " + ((value & i) > 0 ? 1 : 0));

나는 생각 System.out.println하고 &내장 되어 있습니다;)
David Williams

1
방금 3 년 동안의 대답을 말한 것을 깨달았습니다 ... lol.
rajugaadu

7
public static void main(String[] args) 
{
    int i = 13;
    short s = 13;
    byte b = 13;

    System.out.println("i: " + String.format("%32s", 
            Integer.toBinaryString(i)).replaceAll(" ", "0"));

    System.out.println("s: " + String.format("%16s", 
            Integer.toBinaryString(0xFFFF & s)).replaceAll(" ", "0"));

    System.out.println("b: " + String.format("%8s", 
            Integer.toBinaryString(0xFF & b)).replaceAll(" ", "0"));

}

산출:

i: 00000000000000000000000000001101
s: 0000000000001101
b: 00001101

6

이 논리가 숫자를 어떤 기본으로 변환 할 수 있는지 확인하십시오.

public static void toBase(int number, int base) {
    String binary = "";
    int temp = number/2+1;
    for (int j = 0; j < temp ; j++) {
        try {
            binary += "" + number % base;

            number /= base;
        } catch (Exception e) {
        }
    }
    for (int j = binary.length() - 1; j >= 0; j--) {
        System.out.print(binary.charAt(j));
    }
}

또는

StringBuilder binary = new StringBuilder();
int n=15;
while (n>0) {
    if((n&1)==1){
        binary.append(1);
    }else
        binary.append(0);
    n>>=1;
}
System.out.println(binary.reverse());

1
0으로 입력하기 위해`if (a == 0) {binary.append (0); System.out.println (binary.toString ()); 반환; }`while 루프 위의 두 번째 솔루션에이 줄을 추가해야합니다.
Imran

4

이것은 정수 의 내부 이진 표현 을 인쇄 하는 가장 간단한 방법 입니다 . 예를 들어 : n을 17로 사용하면 출력은 다음과 같습니다. 0000 0000 0000 0000 0000 0000 0001 0001

void bitPattern(int n) {

        int mask = 1 << 31;
        int count = 0;
        while(mask != 0) {
            if(count%4 == 0)
                System.out.print(" ");

            if((mask&n) == 0) 

                System.out.print("0");



            else 
                System.out.print("1");


            count++;
            mask = mask >>> 1;


    }
    System.out.println();
}

4

간단히 해보십시오. 범위가 주어진 정수 값의 이진 값만 인쇄하는 경우. 긍정적이거나 부정적 일 수 있습니다.

      public static void printBinaryNumbers(int n) {
        char[] arr = Integer.toBinaryString(n).toCharArray();
        StringBuilder sb = new StringBuilder();
        for (Character c : arr) {
          sb.append(c);
        }
        System.out.println(sb);
      }

입력

5

산출

101


2

32 비트 디스플레이 마스크를 사용하는 솔루션

public static String toBinaryString(int n){

    StringBuilder res=new StringBuilder();
    //res= Integer.toBinaryString(n); or
    int displayMask=1<<31;
    for (int i=1;i<=32;i++){
        res.append((n & displayMask)==0?'0':'1');
        n=n<<1;
        if (i%8==0) res.append(' ');
    }

    return res.toString();
}


 System.out.println(BitUtil.toBinaryString(30));


O/P:
00000000 00000000 00000000 00011110 

2

간단하고 매우 쉬운 솔루션.

public static String intToBinaryString(int integer, int numberOfBits) {

    if (numberOfBits > 0) {     // To prevent FormatFlagsConversionMismatchException.

        String nBits = String.format("%" + numberOfBits + "s",      // Int to bits conversion
                Integer.toBinaryString(integer))
                .replaceAll(" ","0"); 

        return nBits;   // returning the Bits for the given int.
    }

    return null;        // if the numberOfBits is not greater than 0, returning null.
}

1

이 질문에 대한 좋은 답변이 여기에 게시되어 있습니다. 그러나 이것이 내가 시도한 방법입니다 (그리고 가장 쉬운 논리 기반 → modulo / divide / add ).

        int decimalOrBinary = 345;
        StringBuilder builder = new StringBuilder();

        do {
            builder.append(decimalOrBinary % 2);
            decimalOrBinary = decimalOrBinary / 2;
        } while (decimalOrBinary > 0);

        System.out.println(builder.reverse().toString()); //prints 101011001

0

이 질문은 자바에서 까다 롭습니다 (아마도 다른 언어로도 가능).

Integer는 32 비트 부호있는 데이터 형식이지만 Integer.toBinaryString ()은 정수 인수의 문자열 표현을 기수 2 의 부호없는 정수 로 반환합니다 .

따라서 Integer.parseInt (Integer.toBinaryString (X), 2)는 예외 (서명 된 대 서명되지 않은)를 생성 할 수 있습니다.

안전한 방법은 Integer.toString (X, 2); 이것은 덜 우아한 것을 생성합니다 :

-11110100110

그러나 작동합니다 !!!


그는 파싱하지 않고 인쇄하려고합니다.
Lorne의 후작

System.out.println (정수. 문자열 (X, 2));
닌자

0

내장 알고리즘을 사용하지 않으려는 사람들에게는 지금까지 가장 간단한 알고리즘이라고 생각합니다.

public static String convertNumber(int a)  { 
              StringBuilder sb=new StringBuilder();
              sb.append(a & 1);
              while ((a>>=1) != 0)  { 
                  sb.append(a & 1);
               }
              sb.append("b0");
              return sb.reverse().toString();
  }

예:

convertNumber (1) -> "0b1"

convertNumber (5) -> "0b101"

convertNumber (117) -> "0b1110101"

작동 방식 : while-loop는 a- 숫자를 오른쪽으로 이동하고 (마지막 비트를 초에서 마지막으로 대체하는 등), 마지막 비트의 값을 가져 와서이를 StringBuilder에 넣고 비트가 없을 때까지 반복합니다. a = 0).


0
    for(int i = 1; i <= 256; i++)
    {
        System.out.print(i + " "); //show integer
        System.out.println(Integer.toBinaryString(i) + " "); //show binary
        System.out.print(Integer.toOctalString(i) + " "); //show octal
        System.out.print(Integer.toHexString(i) + " "); //show hex

    }

3
답변을 주셔서 감사합니다, 그러나 자세한 설명 및 / 또는 정보를 추가하고 질문을 해결하는 방법을 다른 사람이 명확하게 요구하지 않고 쉽게 이해할 수 있도록 추가하십시오 :)
koceeng

0

이 방법으로 시도하십시오 :

public class Bin {
  public static void main(String[] args) {
    System.out.println(toBinary(0x94, 8));
  }

  public static String toBinary(int a, int bits) {
    if (--bits > 0)
        return toBinary(a>>1, bits)+((a&0x1)==0?"0":"1");
    else 
        return (a&0x1)==0?"0":"1";
  }

}

10010100


0

왼쪽 패딩 된 0으로 주어진 int x의 이진 표현 :

org.apache.commons.lang3.StringUtils.leftPad(Integer.toBinaryString(x), 32, '0')

0

입력으로 10 진수를 입력하십시오. 그런 다음 주어진 입력을 이진수로 변환하기 위해 모듈로 및 나누기와 같은 연산을 수행합니다. 다음은 정수 값을 이진으로 변환하기위한 Java 프로그램의 소스 코드와이 이진수의 비트 번호입니다. Java 프로그램이 Windows 시스템에서 성공적으로 컴파일되고 실행되었습니다. 프로그램 출력도 아래에 나와 있습니다.

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int integer ;
        String binary = "";    //   here we count "" or null 
                               //   just String binary = null;
        System.out.print("Enter the binary Number: ");
        integer = sc.nextInt();

        while(integer>0)
        {
            int x = integer % 2;
            binary = x + binary;
            integer = integer / 2;  
        }
        System.out.println("Your binary number is : "+binary);
        System.out.println("your binary length : " + binary.length());
    }
}

0

응답이 없으므로 바이너리 파일에 정수를 저장하는 방법에 대한 질문 일 것입니다. java.io.DataOutputStream은 당신이 찾고있는 것일 수 있습니다 : https://docs.oracle.com/javase/8/docs/api/java/io/DataOutputStream.html

DataOutputStream os = new DataOutputStream(outputStream);
os.writeInt(42);
os.flush();
os.close();

2
대부분의 시간 인쇄는 파일에 저장하지 않고 콘솔에 무언가를 쓰는 것을 의미합니다. 데이터를 파일로 직렬화하도록 요청하면 답이 유용 할 수 있습니다.
Alain-Michel Chomnoue N

물론 그 질문을받은 사람이 대답을 받아들이지 않았기 때문에 그의 질문이 정확하지 않다고 생각했습니다.
기독교 Charbula

0

비트 마스크 (1 << k)를 사용하고 숫자로 AND 연산을 수행 할 수 있습니다! 1 << k는 k 위치에 1 비트입니다!

private void printBits(int x) {
    for(int i = 31; i >= 0; i--) {
        if((x & (1 << i)) != 0){
            System.out.print(1);
        }else {
            System.out.print(0);
        }
    }
    System.out.println();
}

-2

강력한 비트 조작에 사용되는 부호있는 값과 부호없는 값으로 작동하며 왼쪽에서 첫 번째 0을 생성합니다.

public static String representDigits(int num) {

        int checkBit = 1 << (Integer.SIZE * 8 - 2 );    // avoid the first digit        
        StringBuffer sb = new StringBuffer();

        if (num < 0 ) {     // checking the first digit
            sb.append("1");
        } else {
            sb.append("0");
        }

        while(checkBit != 0) {          
            if ((num & checkBit) == checkBit){
                sb.append("1");
            } else {
                sb.append("0");
            }           
            checkBit >>= 1;     
        }       

        return sb.toString();
    }
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.