从hex / binary序列中获取每个位

时间:2014-03-12 19:36:21

标签: java

我想将程序变量mesaj作为int(hexa或binary),但.getBytes()不适用于整数。我可以使用什么?

public static void main(String[] args) {
        int crc = 0xFFFF;       // 65535 sau 111...de 16 ori
        int polinom = 0x1021;   // 0001 0000 0010 0001  (0, 5, 12) 

        // byte[] testBytes = "123456789".getBytes("ASCII");

        String mesaj = "1111111";// I want this to be an integer
        byte[] bytes = mesaj.getBytes();//this won't work on an int

        for (int n = 0; n < bytes.length; n++) {
            byte b = bytes[n];//iau byte cu byte


            for (int i = 0; i < 8; i++) {//iau bit cu bit al fiecarui byte

                //convertesc in sir de biti, si iau numai bitii care sunt 1
                boolean bit = ((b >> (7 - i) & 1) == 1);
                //la fel si fiecare bit al crc-ului curent
                boolean c15 = ((crc >> 15 & 1) == 1);

                crc <<= 1;


                if (c15 ^ bit) {//daca XOR pe c15 si bit da 1

                    crc ^= polinom;

                } 
            }
        }

        crc &= 0xffff;


        System.out.println("Hexa: " + Integer.toString(crc, 16));
        System.out.println("Zecimal: " + Integer.toString(crc));
        System.out.println("Binar: " + Integer.toBinaryString(crc));
    }

1 个答案:

答案 0 :(得分:3)

您可能希望实际解析为int,例如<{1}}或Integer.parseInt(mesaj, 2)表示十六进制数。