public class IPconversion {
public void integertoip(int a){
String b = Integer.toBinaryString(a);
int l = 32 - b.length();
StringBuilder builder = new StringBuilder();
String [] arr = new String[l];
for(int k =0; k<arr.length; k++){
arr[k] = "0";
}
for(int i = 0;i<arr.length;i++){
builder.append(arr[i]);
}
String m = builder.toString();
b = m+b; //adds missing zeros to represent all 32 bits
StringBuilder input1 = new StringBuilder();
input1.append(b);
input1=input1.reverse(); //reverses the 32 bit binary string
System.out.println(input1);
String c = input1.toString();
int len = 8;
String regex = "(?<=^|\\G.{" + len + "})";
String [] parts = c.split (regex); //stores 8 bits chunks in array
for(int i =0; i<parts.length; i++){
StringBuilder input2 = new StringBuilder();
input2.append(parts[i]);
input2=input2.reverse(); //reverses the 8 bits chunks
parts[i] = input2.toString();
System.out.println(parts[i]);
}
for(int g =0; g<parts.length; g++){
double Sum=0;
for(int h=7; h>=0; h--){
char s = parts[g].charAt(h); //error on this line
int y = Character.getNumericValue(s);
Sum = Sum+(Math.pow(2,7-h)*y); //computes decimal value
}
Double d = new Double(Sum);
int i = d.intValue();
System.out.println(i+".");
}
}
public static void main(String[] args) {
IPconversion object = new IPconversion();
object.integertoip(167840383);
}
}
所以我想寫一個代碼,將4字節整數轉換爲點分十進制(IP地址),但我得到這個錯誤。任何人都可以告訴我爲什麼我得到這個錯誤?該字符串有8個字符!字符串索引超出範圍(轉換整數到IP)
輸出:
11111110010100001000000001010000
01111111
00001010
00000001
00001010
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 7
at java.lang.String.charAt(String.java:658)
at ipconversion.IPconversion.integertoip(IPconversion.java:66)
at ipconversion.IPconversion.main(IPconversion.java:86)
Java Result: 1
你確定你使用這段代碼嗎?它似乎爲我工作 – SomeJavaGuy
此代碼工作正常只是測試它 –
@KevinEsche是我使用此代碼,但每次我運行它它會給出此錯誤。 –