我在 javascript 中找到了一个简单而漂亮的 Base64 库,并想从中创建一个 java 类(我知道用于此目的的现有 java 库!但我不感兴趣)。所以这是一段使用 isNaN 的 javascript 代码。我需要一个 java 等价物
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
并包含javascript函数:
// private property
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
private static final Integer NaN = 0;
public static String encode(String input){
StringBuffer output = new StringBuffer();
int chr1 = 0, chr2 = 0, chr3 = 0;
int enc1, enc2, enc3, enc4;
int i = 0;
input = _utf8_encode(input);
while (i < input.length()) {
//before: chr1 = Character.codePointAt(input, i++);
if (i+1>=input.length()){
chr1 = NaN;
i++;
} else {
chr1 = Character.codePointAt(input, i++);
}
if (i+1>=input.length()){
chr2 = NaN;
i++;
} else {
chr2 = Character.codePointAt(input, i++);
}
if (i+1>=input.length()){
chr3 = NaN;
i++;
} else {
chr3 = Character.codePointAt(input, i++);
}
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
//System.out.println(chr2+ " -> "+ String.valueOf(Character.toChars(chr2)) + "| "+String.valueOf(Character.toChars(chr2)).length());
//System.out.println(chr3+ " -> "+ String.valueOf(Character.toChars(chr3)) + "| "+String.valueOf(Character.toChars(chr3)).length());
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output.append(_keyStr.charAt(enc1))
.append(_keyStr.charAt(enc2))
.append(_keyStr.charAt(enc3))
.append(_keyStr.charAt(enc4));
}
return output.toString();
}
private static boolean isNaN(int charCodePoint){
if(charCodePoint==NaN)
return true;
else
return false;
}
我在 java 中的最后一次尝试是使用:
Character.isDigit((char)chr2).. 不行..
见 isNaN(int charCodePoint) .. 也不行
并包含java等效函数:
//String _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
public static String encode(String input){
StringBuffer output = new StringBuffer();
int chr1, chr2, chr3;
int enc1, enc2, enc3, enc4;
int i = 0;
input = _utf8_encode(input);
while (i < input.length()) {
chr1 = Character.codePointAt(input, i++);
chr2 = Character.codePointAt(input, i++);
chr3 = Character.codePointAt(input, i++);
enc1 = (chr1 >> 2);
enc2 = (((chr1 & 3) << 4) | (chr2 >> 4));
enc3 = (((chr2 & 15) << 2) | (chr3 >> 6));
enc4 = (chr3 & 63);
if (Character.isDigit((char)chr2)==false) {
enc3 = enc4 = 64;
} else if (Character.isDigit((char)chr3)==false) {
enc4 = 64;
}
output.append(_keyStr.charAt(enc1))
.append(_keyStr.charAt(enc2))
.append(_keyStr.charAt(enc3))
.append(_keyStr.charAt(enc4));
}
return output.toString();
}
什么是正确的 java 等效于 javascript 的 isNaN 函数?