개발

Sample Method (toBinary, fromBinary)

JUNIT74 2020. 12. 17. 13:18
    static String toBinary(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * Byte.SIZE);
        for( int i = 0; i < Byte.SIZE * bytes.length; i++ )
            sb.append((bytes[i / Byte.SIZE] << i % Byte.SIZE & 0x80) == 0 ? '0' : '1');
        return sb.toString();
    }

    static byte[] fromBinary(String s) {
        int sLen = s.length();
        byte[] toReturn = new byte[(sLen + Byte.SIZE - 1) / Byte.SIZE];
        char c;
        for( int i = 0; i < sLen; i++ )
            if( (c = s.charAt(i)) == '1' )
                toReturn[i / Byte.SIZE] = (byte) (toReturn[i / Byte.SIZE] | (0x80 >>> (i % Byte.SIZE)));
            else if ( c != '0' )
                throw new IllegalArgumentException();
        return toReturn;
    }

 

    public static void main(String[] args) {
        byte[] b1 = new byte[] {-125, -34};

        String ret = toBinary(b1);

        System.out.println(ret);
        byte[] b2 = fromBinary(ret);

        for (int idx=0; idx<b2.length; idx++) {
            System.out.println("byte[" + idx + "] : " + + b2[idx]);
        }
    }

위와 같이 테스트 시에 아래와 같은 결과를 얻을 수 있다.

 

1000001111011110
byte[0] : -125
byte[1] : -34