package math.nums;

public class NumsUtil {
    private NumsUtil() {
    }

    //zamienia binarny strong na liczbę w kodzie
    //uzupelnien do 2
    public static int bin2ToInt(String bits8) {
        int temp = Integer.parseInt(bits8, 2);
        if (Integer.parseInt(bits8.substring(0, 1)) == 1) {
            temp -= Math.pow(2, bits8.length());
        }
        return temp;
    }

    //liczba zamienia liczbe int na liczbe w kodzie uzupełnień
    //do 2
    public static String intToBin2(int bajt) {
        String temp = Integer.toBinaryString(bajt);
        int a = temp.length();
        if (a > 8) {
            return temp.substring(a - 8, a);
        } else {
            return temp;
        }
    }

    public static byte[] bin2ToByteArray(String bits) {
        int len = bits.length() / 8;
        byte[] bytes = null;
        int j = 0;
        if (bits.substring(0, 1).equals("1")) {
            bytes = new byte[len + 1];
            bytes[0] = 0;
            j = 1;
        } else {
            bytes = new byte[len];
        }
        for (int i = 0; i < bits.length(); i = i + 8) {
            String s = bits.substring(i, i + 8);
            bytes[j] = (byte) bin2ToInt(s);
            j++;
        }
        return bytes;
    }
}
