Hm, okay.
In Java, how would parse a String, that should be 8 chars long, and contain only zeroes and ones, as a byte ? All 256 values possible?
You want to throw an exception if the String does not comply with these constraints, and you'd rather not include a library just for that.
My attempts so far :
####
static byte parseByte(String s) {
if(Pattern.matches("[01]{8}", s)) {
int parsed = Integer.parseInt(s, 2);
return (byte)parsed;
} else {
throw new IllegalArgumentException("Not a binary byte: " + s);
}
}
####
Or, slighly more efficient:
########
static byte parseByte(String s) {
if(s.length() != 8) {
throw new IllegalArgumentException("Not a binary byte: " + s);
}
byte parsed = 0;
for(int i = 0; i < 8; i++) {
char digit = s.charAt(i);
parsed *= 2;
if(digit == '1') {
parsed++;
} else if(digit != '0') {
throw new IllegalArgumentException("Not a binary byte: " + s);
}
}
return parsed;
}
#####