1 字符串取余操作
当关键字key是一个字符串时,可以将该字符串转化为字节数组。如果关键字key的字符串中没有任何本地语言字符(即全部均为ASCII码),则直接可以转换成字节数组;如果关键字的字符串中可能有本地语言字符,则可以依据本地字符集编码或者通用字符集编码,将字符串转换成字节数组。转化为字节数组后,即可按照字节数组进行取余操作。
在Java程序中,字符串可以按照char类型(unicode编码)进行访问,将char类型直接按照short类型进行处理。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | /** * Get residue of string. * * @param value Value of string. * @param prime A prime for dividing. * @return * <p>Residue of string.</p> */ public static int getResidue(String value, int prime) { //Residue int residue = 0 ; //Each char is divided by prime. for ( int i = 0 ;i < value.length();i ++) { //Get residue. residue = (value.charAt(i) + (residue << 16 )) % prime; } //Return residue. return residue; } |
2 字节数组取余操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | /** * Get residue of byte array. * * @param bytes Byte array. * @param prime A prime for dividing. * @return * <p>Residue of byte array.</p> */ public static int getResidue( byte [] bytes, int prime) { //Residue int residue = 0 ; //Each byte is divided by prime. for ( int i = 0 ;i < bytes.length;i ++) { //Get residue. residue = (bytes[i] + (residue << 8 )) % prime; } //Return residue. return residue; } |