我嘗試了將十六進制轉換爲字節的不同方法,代碼中有四種方法,其中三種我將其註釋掉,只有一種在運行時沒有錯誤,但我困惑的是,當我重複運行代碼時,它給了我不同的結果(應該生成「字節」)。用大字符串將十六進制轉換爲字節
有一個問題,當我使用「method1」,它給了我結果(字節),但是一旦我改變爲「method2」,它不會生成結果,我不知道爲什麼。我認爲它應該產生相同的結果,當我有相同的字符串。
public class Convert {
/**
* @param args
* @throws IOException
*/
// String everything;
public static void main(String[] args) throws IOException {
//String everything;
// TODO Auto-generated method stub
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("C:\\TEMP1\\Doctor.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
StringBuilder sb = new StringBuilder();
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (line != null) {
sb.append(line);
sb.append('\n');
line = br.readLine();
}
//*********Method 1****************
//String r="1ee079746828d7c6f9af46f93c1ef2555ff4b14b2378ad53a258d18dc6a8363fb57f3448783833722bd9ef291ba53153afca31a96de404755e78f68b76fd5a77e4be3b984ea25244842e92a8ed40da1f1a588fb3da26b8bc21d74cd8476534f26ee454df086567c4d7cf3334f794cede41a9b051a5c393a35584afcf";
//byte[] b = new BigInteger(r,16).toByteArray();
//System.out.println("Byte for public key: "+b);
//*********Method 2****************
//String r2 = sb.toString();
//System.out.println("Doctor contect file: "+r2);
//byte[] b = new BigInteger(r2,16).toByteArray();
//System.out.println("Byte for public key: "+b);
//********Method 3*****************
String r="1ee079746828d7c6f9af46f93c1ef2555ff4b14b2378ad53a258d18dc6a8363fb57f3448783833722bd9ef291ba53153afca31a96de404755e78f68b76fd5a77e4be3b984ea25244842e92a8ed40da1f1a588fb3da26b8bc21d74cd8476534f26ee454df086567c4d7cf3334f794cede41a9b051a5c393a35584afcf";
int len = r.length();
byte[] data = new byte[len/2];
for (int i = 0; i < len; i += 2) {
data[i/2] = (byte) ((Character.digit(r.charAt(i), 16) << 4)
+ Character.digit(r.charAt(i+1), 16));
System.out.println(data);
}
//********Method4******************
/*
String r2 = sb.toString();
int len = r2.length();
byte[] data = new byte[len/2];
for (int i = 0; i < len; i += 2) {
data[i/2] = (byte) ((Character.digit(r2.charAt(i), 16) << 4)
+ Character.digit(r2.charAt(i+1), 16));
System.out.println(data);
}
*/
//String r=everything;
// String r="1ee079746828d7c6f9af46f93c1ef2555ff4b14b2378ad53a258d18dc6a8363fb57f3448783833722bd9ef291ba53153afca31a96de404755e78f68b76fd5a77e4be3b984ea25244842e92a8ed40da1f1a588fb3da26b8bc21d74cd8476534f26ee454df086567c4d7cf3334f794cede41a9b051a5c393a35584afcf";
// double convert=Double.parseDouble(r);
// long convert=(long)(Integer.parseInt(r,32)&0xFF);
// byte convert=Byte.parseByte(r,32);
// byte convert=Integer.parseInt(everything,16);
// System.out.println("Byte for public key: "+convert);
} finally {
br.close();
}
}
}
除非這是作業,否則使用DatatypeConverter.parseHexBinary(yourhexstring);將十六進制字符串轉換爲字節數組。 – lreeder
在您發佈的90行代碼中,只有7行與問題相關。請專注於下次只發布*相關*代碼。 –