IT박스

Java에서 정수의 0 패딩 이진 표현을 얻는 방법은 무엇입니까?

itboxs 2020. 8. 7. 08:09
반응형

Java에서 정수의 0 패딩 이진 표현을 얻는 방법은 무엇입니까?


예를 들어 1, 2, 128, 256출력은 (16 자리) 일 수 있습니다.

0000000000000001
0000000000000010
0000000010000000
0000000100000000

나는 시도했다

String.format("%16s", Integer.toBinaryString(1));

왼쪽 패딩을위한 공백을 넣습니다.

`               1'

0패딩 s를 넣는 방법. Formatter 에서 찾을 수 없습니다 . 다른 방법이 있습니까?

추신 이 게시물 은 왼쪽 0 패딩으로 정수 형식을 지정하는 방법을 설명하지만 이진 표현은 아닙니다.


이것이 차선책이라고 생각하지만 할 수 있습니다.

String.format("%16s", Integer.toBinaryString(1)).replace(' ', '0')

java.util.Formatter에 내장 된 바이너리 변환은 없습니다. 다음과 같이 String.replace를 사용하여 공백 문자를 0으로 바꾸는 것이 좋습니다.

String.format("%16s", Integer.toBinaryString(1)).replace(" ", "0")

또는 주어진 라인을 따라 추가 왼쪽 패딩 곳 이진 표현으로 변환 정수로 자신의 논리를 구현 너무. 또는 숫자를 형식으로 전달해야하는 경우 이진 표현을 BigInteger로 변환 한 다음 선행 0으로 형식을 지정할 수 있지만 다음과 같이 런타임시 매우 비용이 많이 듭니다.

String.format("%016d", new BigInteger(Integer.toBinaryString(1)))

Apache Commons StringUtils를 사용할 수 있습니다 . 패딩 문자열에 대한 메소드를 제공합니다.

StringUtils.leftPad(Integer.toBinaryString(1), 16, '0');

저는이 작업을 수행하기 위해 이전에 실제로 사용하지 않은 모든 종류의 메서드 호출을 시도했습니다. 그들은 보통의 성공을 거두었습니다. 제가 너무나도 간단해서 작동 할 수도 있다는 생각이 들기 전까지는 성공했습니다.

나는 그것이 긴 이진 코드 문자열에 대해 좋은지 확실하지 않지만 16Bit 문자열에서는 잘 작동하는지 전에 생각했음을 확신합니다. 도움이 되었기를 바랍니다 !! (두 번째 코드가 개선되었습니다.)

String binString = Integer.toBinaryString(256);
  while (binString.length() < 16) {    //pad with 16 0's
        binString = "0" + binString;
  }

이 답변을 개선하여 루프에서 작동하도록 도움을 준 Will에게 감사드립니다. 조금 어색 할 수도 있지만 작동합니다. 개선하고 가능한 경우 댓글을 달아주세요 ....

binString = Integer.toBinaryString(256);
int length = 16 - binString.length();
char[] padArray = new char[length];
Arrays.fill(padArray, '0');
String padString = new String(padArray);
binString = padString + binString;

여기에 이전 게시물에 대한 새로운 답변이 있습니다.

이진 값을 선행 0으로 특정 길이로 채우려면 다음을 시도하십시오.

Integer.toBinaryString( (1 << len) | val ).substring( 1 )

만약 len = 4val = 1,

Integer.toBinaryString( (1 << len) | val )

문자열을 반환 한 "10001"다음

"10001".substring( 1 )

첫 번째 문자를 버립니다. 그래서 우리는 우리가 원하는 것을 얻습니다.

"0001"

val부정적 일 가능성이있는 경우 다음을 시도하십시오.

Integer.toBinaryString( (1 << len) | (val & ((1 << len) - 1)) ).substring( 1 )

시험...

String.format("%016d\n", Integer.parseInt(Integer.toBinaryString(256)));

나는 이것이 이것을하는 "올바른"방법이라고 생각하지 않는다 ... 그러나 그것은 작동한다 :)


"올바른"해결책은 모르지만 빠른 패치를 제안 할 수 있습니다.

String.format("%16s", Integer.toBinaryString(1)).replace(" ", "0");

I have just tried it and saw that it works fine.


A simpler version of user3608934's idea "This is an old trick, create a string with 16 0's then append the trimmed binary string you got ":

private String toBinaryString32(int i) {
    String binaryWithOutLeading0 = Integer.toBinaryString(i);
    return "00000000000000000000000000000000"
            .substring(binaryWithOutLeading0.length())
            + binaryWithOutLeading0;
}

A naive solution that work would be

String temp = Integer.toBinaryString(5);
while (temp.length() < Integer.SIZE) temp = "0"+temp; //pad leading zeros
temp = temp.substring(Integer.SIZE - Short.SIZE); //remove excess

One other method would be

String temp = Integer.toBinaryString((m | 0x80000000));
temp = temp.substring(Integer.SIZE - Short.SIZE);

This will produce a 16 bit string of the integer 5


This is an old trick, create a string with 16 0's then append the trimmed binary string you got from String.format("%s", Integer.toBinaryString(1)) and use the right-most 16 characters, lopping off any leading 0's. Better yet, make a function that lets you specify how long of a binary string you want. Of course there are probably a bazillion other ways to accomplish this including libraries, but I'm adding this post to help out a friend :)

public class BinaryPrinter {

    public static void main(String[] args) {
        System.out.format("%d in binary is %s\n", 1, binaryString(1, 4));
        System.out.format("%d in binary is %s\n", 128, binaryString(128, 8));
        System.out.format("%d in binary is %s\n", 256, binaryString(256, 16));
    }

    public static String binaryString( final int number, final int binaryDigits ) {
        final String pattern = String.format( "%%0%dd", binaryDigits );
        final String padding = String.format( pattern, 0 );
        final String response = String.format( "%s%s", padding, Integer.toBinaryString(number) );

        System.out.format( "\npattern = '%s'\npadding = '%s'\nresponse = '%s'\n\n", pattern, padding, response );

        return response.substring( response.length() - binaryDigits );
    }
}

I would write my own util class with the method like below

public class NumberFormatUtils {

public static String longToBinString(long val) {
    char[] buffer = new char[64];
    Arrays.fill(buffer, '0');
    for (int i = 0; i < 64; ++i) {
        long mask = 1L << i;
        if ((val & mask) == mask) {
            buffer[63 - i] = '1';
        }
    }
    return new String(buffer);
}

public static void main(String... args) {
    long value = 0b0000000000000000000000000000000000000000000000000000000000000101L;
    System.out.println(value);
    System.out.println(Long.toBinaryString(value));
    System.out.println(NumberFormatUtils.longToBinString(value));
}

}

Output:

5
101
0000000000000000000000000000000000000000000000000000000000000101

The same approach could be applied to any integral types. Pay attention to the type of mask

long mask = 1L << i;


This method converts an int to a String, length=bits. Either padded with 0s or with the most significant bits truncated.

static String toBitString( int x, int bits ){
    String bitString = Integer.toBinaryString(x);
    int size = bitString.length();
    StringBuilder sb = new StringBuilder( bits );
    if( bits > size ){
        for( int i=0; i<bits-size; i++ )
            sb.append('0');
        sb.append( bitString );
    }else
        sb = sb.append( bitString.substring(size-bits, size) );

    return sb.toString();
}

You can use lib https://github.com/kssource/BitSequence. It accept a number and return bynary string, padded and/or grouped.

String s = new BitSequence(2, 16).toBynaryString(ALIGN.RIGHT, GROUP.CONTINOUSLY));  
return  
0000000000000010  

another examples:

[10, -20, 30]->00001010 11101100 00011110
i=-10->00000000000000000000000000001010
bi=10->1010
sh=10->00 0000 0000 1010
l=10->00000001 010
by=-10->1010
i=-10->bc->11111111 11111111 11111111 11110110

for(int i=0;i<n;i++)
{
  for(int j=str[i].length();j<4;j++)
  str[i]="0".concat(str[i]);
}

str[i].length() is length of number say 2 in binary is 01 which is length 2 change 4 to desired max length of number. This can be optimized to O(n). by using continue.


// Below will handle proper sizes

public static String binaryString(int i) {
    return String.format("%" + Integer.SIZE + "s", Integer.toBinaryString(i)).replace(' ', '0');
}

public static String binaryString(long i) {
    return String.format("%" + Long.SIZE + "s", Long.toBinaryString(i)).replace(' ', '0');
}

import java.util.Scanner;
public class Q3{
  public static void main(String[] args) {
    Scanner scn=new Scanner(System.in);
    System.out.println("Enter a number:");
    int num=scn.nextInt();
    int numB=Integer.parseInt(Integer.toBinaryString(num));
    String strB=String.format("%08d",numB);//makes a 8 character code
    if(num>=1 && num<=255){
     System.out.println(strB);
    }else{
        System.out.println("Number should be in range between 1 and 255");
    }
  }
}

참고URL : https://stackoverflow.com/questions/4421400/how-to-get-0-padded-binary-representation-of-an-integer-in-java

반응형