将输出更改为4x4矩阵

时间:2015-09-18 21:09:38

标签: java encryption methods parity

所以我正在研究Java中的方法,它基本上采用随机字符串然后通过该方法并将字符串更改为奇偶校验位,这基本上是将每个字符转换为二进制数字值。 / p>

这就是我所拥有的:

processNextStep()

这是将字符串转换为4x4矩阵的代码:

public class ShiftData {
    //this is the method that where Logic is implemented..
    static String shiftRows(String text) {
        //character array to store given String elements into an array..
        char[] chs = text.toCharArray();
        StringBuffer samBuffer = new StringBuffer();
        //loop through the length of the character array..
        for (int i = 0; i < chs.length; i++) {
            //adding characters to the StringBuffer...
            samBuffer.append(Integer.toHexString((int) chs[i]));
//            here in the above statement toHexString method pads parity bit and converts to hexadecimal value..
        }
        return samBuffer.toString();//returning the value
    }
}

所以基本上如果输入字符串是:if(text !=null && !text.isEmpty()) { int len = text.length(); int rem = len %16; int padChars = 16-rem; for(int i =0; i < (len+padChars); i++) { if(i < len) { System.out.print(text.charAt(i)+ " "); } else { System.out.print( "A "); } if((i+1) % 4 == 0) System.out.println(); if((i+1) % 16 == 0) System.out.println("\n"); } }

输出应如下所示:

WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO

我只需要帮助结合代码!我可以让他们单独工作,但我无法得到我需要的输出。请说明您将如何编码。

1 个答案:

答案 0 :(得分:1)

不要使用StringBuffer。请改用StringBuilder

您的打印循环一次写入一个字母,以3个空格(和换行符)分隔。十六进制的字母由两个十六进制数字组成,正如您已在所需的输出中显示的那样,因此不会起作用。

您的代码在最后打印空白行,您可能不想要。

如果值为0-15,

Integer.toHexString()将返回一位数。

static String shiftRows(String text) {
    char[] chs = text.toCharArray();
    StringBuilder samBuffer = new StringBuilder();
    for (int i = 0; i < chs.length; i++)
        samBuffer.append(String.format("%02x", (int)chs[i])); // always 2 hex digits, even for 0-15
    return samBuffer.toString();
}

public static void main(String[] args) {
    String text = shiftRows("WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO");
    if (text != null && ! text.isEmpty()) {
        int len = (text.length() + 31) / 32 * 32; // round up to next increment of 32 (16 hex pairs)
        for (int i = 0; i < len; i += 2) {
            if (i != 0 && i % 8 == 0) { // every 4 hex pairs, but not first time
                System.out.println();
                if (i % 32 == 0) // every 16 hex pairs
                    System.out.println();
            }
            if (i < text.length())
                System.out.print(text.substring(i, i + 2) + " ");
            else
                System.out.print("41 ");
        }
    }
}