gpt4 book ai didi

java - java 二进制字符串转十六进制字符串

转载 作者:行者123 更新时间:2023-12-02 08:02:57 32 4
gpt4 key购买 nike

我这里有这段代码,它获取纯文本,并将其转换为 512 位二进制字符串。然后,我想将字符串的每个 32 位部分转换为 8 位十六进制字符串,但这部分给了我一个 java.lang.NumberFormatException

// ----- Turning the message to bits
byte[] binaryS = s.getBytes("UTF-8");
String mesInBinary = "";
for (byte b : binaryS) {
mesInBinary += '0' + Integer.toBinaryString(b);
}
// ----- Message padding & Pre-Processing
// Binary representation of the length of the message in bits
String mesBitLength = Integer.toBinaryString(mesInBinary.length());
// We need the size of the message in 64-bits, so we'll
// append zeros to the binary length of the message so
// we get 64-bit
String appendedZeros = "";
for (int i = 64 - mesBitLength.length() ; i > 0 ; i--)
appendedZeros += '0';
// Calculating the k zeros to append to the message after
// the appended '1'
int numberOfZeros = (448 - (mesInBinary.length() + 1)) % 512;
// Append '1' to the message
mesInBinary += '1';
// We need a positive k
while (numberOfZeros < 0)
numberOfZeros += 512;
for (int i = 1 ; i <= numberOfZeros ; i++)
mesInBinary += '0';
// append the message length in 64-bit format
mesInBinary += appendedZeros + mesBitLength;
System.out.println(mesInBinary);
// ----- Parsing the padded message
// Breaking the message to 512-bit pieces
// And each piece, to 16 32-bit word blocks
String[] chunks = new String[mesInBinary.length() / 512];
String[] words = new String[64 * chunks.length];
for (int i = 0 ; i < chunks.length ; i++) {
chunks[i] = mesInBinary.substring((512 * i), (512 * (i + 1)));
// Break each chunk to 16 32-bit blocks
for (int j = 0 ; j < 16 ; j++) {
words[j] = Long.toHexString(Long.parseLong(chunks[i].substring((32 * j), (32 * (j + 1)))));
}
}

最后一行代码是有问题的,我得到了执行。有什么建议吗?

最佳答案

最后一个语句*应该指定基数2,我认为:

words[j] = Long.toHexString(
Long.parseLong(chunks[i].substring((32 * j), (32 * (j + 1))), 2));

*不是最后一行代码,MДДГ:-)

关于java - java 二进制字符串转十六进制字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8627375/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com