JNI技巧
char*转jbyteArray
jbyteArray getByteArray(JNIEnv *env,const char* buf, int len){
jbyteArray byteArray = env->NewByteArray(len);
jbyte* bytes = ( jbyte* )buf;
env->SetByteArrayRegion(byteArray, 0, len, bytes);
free((void *)buf);
return byteArray;
}
jstring转string
string getString(JNIEnv *env, jstring javaString){
const char *str = env->GetStringUTFChars(javaString, JNI_FALSE);
string ret = string(str);
env->ReleaseStringUTFChars(javaString, str);
return ret;
}
char*, string转jstring
jstring Tools::getJString(JNIEnv *env, string str){
return getJString(env, str.c_str(), str.length());
}
jstring Tools::getJString(JNIEnv *env, const char *buf, int len){
return env->NewStringUTF(buf);
}
Java技巧
byte[]转16进制字符串
public static String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2*buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private final static String HEX = "0123456789ABCDEF";
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
}
16进制字符串转byte[]
public static byte[] toByte(String hexString) {
int len = hexString.length()/2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
return result;
}
网友评论