(Java) 이진 번호를 문자열로 변환 할 때 비트 수 (길이) 수를 지정합니까?

StackOverflow https://stackoverflow.com/questions/625838

  •  05-07-2019
  •  | 
  •  

문제

배열에 바이너리 스트링으로 숫자를 저장하려고하지만 저장하려면 비트를 얼마나 많이 보관 해야하는지 지정해야합니다.

예를 들어, 0을 두 개의 비트로 저장 해야하는 경우 문자열 "00"이 필요합니다. 또는 "001010"6 비트로 1010.

누구든지 도울 수 있습니까?

편집 : 감사합니다. 수학/프로그래밍에서 쓰레기를 쓰다듬으므로 David 's 인 가장 간단한 솔루션을 사용했습니다. 같은 것 :

binaryString.append(Integer.toBinaryString(binaryNumber));
for(int n=binaryString.length(); n<numberOfBits; n++) {
                        binaryString.insert(0, "0");
}

잘 작동하는 것 같습니다. 매우 비효율적이지 않으면 함께 갈 것입니다.

도움이 되었습니까?

해결책

사용 Integer.toBinaryString() 그런 다음 문자열 길이를 확인하고 원하는 길이를 만들기 위해 필요한만큼의 0으로 전제하십시오.

다른 팁

집에서 만든 솔루션을 잊어 버리십시오. 표준을 사용하십시오 Biginteger 대신에. 비트 수를 지정한 다음 Tostring (int radix) 메소드를 사용하여 필요한 것을 복구 할 수 있습니다 (Radix = 2가 필요하다고 가정합니다).

편집하다: 나는 Biginteger에게 비트 제어를 남길 것입니다. 객체는 새로운 숫자 차원에 맞게 비트 버퍼를 내부적으로 조정합니다. 또한 산술 작업은이 객체를 통해 수행 될 수 있습니다 (이진 부가자/승수 등을 구현할 필요는 없습니다). 다음은 기본 예입니다.

package test;

import java.math.BigInteger;

public class TestBigInteger
{
    public static void main(String[] args)
    {
        String value = "1010";
        BigInteger bi = new BigInteger(value,2);
        // Arithmetic operations
        System.out.println("Output: " + bi.toString(2));
        bi = bi.add(bi); // 10 + 10
        System.out.println("Output: " + bi.toString(2));
        bi = bi.multiply(bi); // 20 * 20
        System.out.println("Output: " + bi.toString(2));

        /*
         * Padded to the next event number of bits
         */
        System.out.println("Padded Output: " + pad(bi.toString(2), bi.bitLength() + bi.bitLength() % 2));
    }

    static String pad(String s, int numDigits)
    {
        StringBuffer sb = new StringBuffer(s);
        int numZeros = numDigits - s.length();
        while(numZeros-- > 0) { 
            sb.insert(0, "0");
        }
        return sb.toString();
    }
}

이것은 일반적인 숙제 문제입니다. 2의 가장 작은 전력을 계산할 수있는 멋진 루프가 있습니다. N.

2의 힘이므로 Base 2 로그는 비트 수입니다. 그러나 자바 math 라이브러리는 자연 로그 만 제공합니다.

math.log( n ) / math.log(2.0) 

비트 수입니다.

더 간단하게 :

String binAddr = Integer.toBinaryString(Integer.parseInt(hexAddr, 16));  
String.format("%032", new BigInteger(binAddr)); 

여기서 아이디어는 문자열을 일시적으로 소수점으로 다시 구문 분석하는 것입니다 (하나는 모두 1과 0으로 구성되어있는 것)가 string.format ()를 사용하는 것입니다.

이진 문자열은 정수를 빠르게 넘치고 오랫동안 사용하려는 경우 NumberformateXceptions를 초래하기 때문에 기본적으로 BigInteger를 사용해야합니다. Integer.fromString() 또는 Long.fromString().

이 시도:

String binaryString = String.format("%"+Integer.toString(size)+"s",Integer.toBinaryString(19)).replace(" ","0");

크기는 사용자가 원하는 숫자가 될 수 있습니다

다음은 간단한 솔루션입니다 int 값; 바이트 등으로 확장하는 방법은 분명해야합니다.

public static String bitString(int i, int len) {
    len = Math.min(32, Math.max(len, 1));
    char[] cs = new char[len];
    for (int j = len - 1, b = 1; 0 <= j; --j, b <<= 1) {
        cs[j] = ((i & b) == 0) ? '0' : '1';
    }
    return new String(cs);
}

다음은 샘플 테스트 사례 세트의 출력입니다.

  0   1                                0                                0
  0  -1                                0                                0
  0  40 00000000000000000000000000000000 00000000000000000000000000000000
 13   1                                1                                1
 13   2                               01                               01
 13   3                              101                              101
 13   4                             1101                             1101
 13   5                            01101                            01101
-13   1                                1                                1
-13   2                               11                               11
-13   3                              011                              011
-13   4                             0011                             0011
-13   5                            10011                            10011
-13  -1                                1                                1
-13  40 11111111111111111111111111110011 11111111111111111111111111110011

물론, 당신은 길이 매개 변수를 전체 값을 표현하기에 적합하게 만들 수 있습니다.

import java.util.BitSet;

public class StringifyByte {

    public static void main(String[] args) {
        byte myByte = (byte) 0x00;
        int length = 2;
        System.out.println("myByte: 0x" + String.valueOf(myByte));
        System.out.println("bitString: " + stringifyByte(myByte, length));

        myByte = (byte) 0x0a;
        length = 6;
        System.out.println("myByte: 0x" + String.valueOf(myByte));
        System.out.println("bitString: " + stringifyByte(myByte, length));
    }

    public static String stringifyByte(byte b, int len) {
        StringBuffer bitStr = new StringBuffer(len);
        BitSet bits = new BitSet(len);
        for (int i = 0; i < len; i++)
        {
           bits.set (i, (b & 1) == 1);
           if (bits.get(i)) bitStr.append("1"); else bitStr.append("0");
           b >>= 1;
        }
        return reverseIt(bitStr.toString());
    }

    public static String reverseIt(String source) {
        int i, len = source.length();
        StringBuffer dest = new StringBuffer(len);

        for (i = (len - 1); i >= 0; i--)
           dest.append(source.charAt(i));
        return dest.toString();
    }
}

산출:

myByte: 0x0
bitString: 00
myByte: 0x10
bitString: 001010

따라서 여기 8 대신 원하는 길이를 쓸 수 있으며 그에 따라 0을 추가합니다. 언급 된 정수의 길이가 언급 된 숫자의 길이를 초과하는 경우, 어떤 제로도 추가되지 않습니다.

String.format("%08d",1111);

출력 : 00001111

String.format("%02d",1111);

출력 : 1111

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top