public class HKID {
public static boolean validate(String prefix, String serial, String checkdigit) {
String prefixU = prefix.toUpperCase();
long value = 0; if (prefixU.length() == 2) {
value += (prefixU.charAt(0) - 55) * 9 + (prefixU.charAt(1) - 55) * 8;
} else if (prefixU.length() == 1) {
value += 36 * 9 + (prefixU.charAt(0) - 55) * 8;
}
for (int i = 0; i < 6; i++) {
value += Integer.parseInt(serial.substring(i, i + 1)) * (7 - i);
}
long reminder = value % 11;
long valid_checkdigit = 11 - reminder;
if ("A".equalsIgnoreCase(checkdigit) && valid_checkdigit == 10) {
return true;
}
try {
if (valid_checkdigit == Integer.parseInt(checkdigit)) {
return true;
}
} catch (Exception e) { }
return false;
}
}
PS> Objective-C version
#import "HKID.h"
@implementation HKID
+ (BOOL) validateWithPrefix:(NSString*) prefix serial:(NSString *) serial checkdigit:(NSString*) checkdigit {
NSString* prefixU = [prefix uppercaseString];
int value = 0;
if ([prefixU length] == 2) {
value += (([prefixU characterAtIndex:0] - 55) * 9) + (([prefixU characterAtIndex:1] - 55) * 8);
} else if ([prefixU length] == 1) {
value += 36 * 9 + ([prefixU characterAtIndex:0] - 55) * 8;
} else {
return false;
}
if ([serial length] != 6) return false;
if ([checkdigit length] != 1) return false;
for (int i = 0; i < 6; i++) {
int tempValue = [[serial substringWithRange:NSMakeRange(i,1)] intValue];
value += tempValue * (7 - i);
}
long reminder = value % 11;
long valid_checkdigit = 11 - reminder;
NSCharacterSet *digitSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
if ([[checkdigit stringByTrimmingCharactersInSet:digitSet] isEqualToString:@""]){ // all digits
if ([checkdigit intValue] == valid_checkdigit) {
return true;
}
} else if ([@"A" isEqualToString:checkdigit]) {
if (valid_checkdigit == 10) {
return true;
} else {
return false;
}
}
return false;
}
@end
沒有留言:
張貼留言