I'm implementing a bencoding system for a torrent downloading system I'm making.
Bencoding a string is very easy, you take a string, for instance "hello", and you encode it by writing the string length + a ':' character, followed by the string itself. Bencoded "hello" will be "5:hello"
Currently I'm having this code.
public BencodeString(String string) {
this.string = string;
}
public static BencodeString parseBencodeString(String string) {
byte[] bytes = string.getBytes();
int position = 0;
int size = 0;
StringBuilder sb = new StringBuilder();
while (bytes[position] >= '0' && bytes[position] <= '9') {
sb.append((char) bytes[position]);
position++;
}
if (bytes[position] != ':')
return null;
size = Integer.parseInt(sb.toString());
System.out.println(size);
if (size <= 0)
return null;
return new BencodeString(string.substring(position + 1, size + position
+ 1));
}
It works, but I have the feeling that it could be done ways better. What is the best way to do this?
Note: the string could be any size (thus more than one digit before the string)
Solved already, thanks to everybody that replied here :)