JNI中的C语言实现字节间转换

char转成十六进制字符串:

jstring  charToJString(JNIEnv *env, char* inputChars) {
//    const char* inputChars = env->GetStringUTFChars( input, 0);
    // 对于每个字符,你需要两个字符来表示其十六进制形式,再加上字符串的结束符。
    char hexString[strlen(inputChars) * 2 + 1];
    int i, j = 0;
    for(i = 0; inputChars[i] != '\0'; i++) {
        sprintf(hexString + j, "%02x", (unsigned char)inputChars[i]);
        j += 2;
    }
//    env->ReleaseStringUTFChars( input, inputChars);

    return env->NewStringUTF(hexString);
}

将char转成字符串

jstring char2Jstring(JNIEnv *env, const char *pat) {
    if (pat == nullptr) {
        return nullptr;
    }
    jclass strClass = env->FindClass("java/lang/String");
    jmethodID ctorID = env->GetMethodID(strClass, "", "([BLjava/lang/String;)V");
    jbyteArray bytes = env->NewByteArray(strlen(pat));
    env->SetByteArrayRegion(bytes, 0, strlen(pat), (jbyte *) pat);
    jstring encoding = env->NewStringUTF("UTF-8");
    auto res = (jstring) env->NewObject(strClass, ctorID, bytes, encoding);
    env->DeleteLocalRef(encoding);
    env->DeleteLocalRef(bytes);
    env->DeleteLocalRef(strClass);
    return res;
}

将jstring转成char

char *jstring2Char(JNIEnv *env, jstring jstr) {
    char *rtn = nullptr;
    if (jstr == nullptr) {
        return rtn;
    }
    jclass clsstring = env->FindClass("java/lang/String");
    jstring strencode = env->NewStringUTF("UTF-8");
    jmethodID mid = env->GetMethodID(clsstring, "getBytes", "(Ljava/lang/String;)[B");
    auto barr = (jbyteArray) env->CallObjectMethod(jstr, mid, strencode);
    if (barr != nullptr) {
        jsize alen = env->GetArrayLength(barr);
        jbyte *ba = env->GetByteArrayElements(barr, JNI_FALSE);
//        LOGD("testjni jstring2Char ba:%s", ba);
        if (alen > 0) {
            rtn = (char *) malloc(alen + 1);
            memcpy(rtn, ba, alen);
            rtn[alen] = 0;
        }
        env->ReleaseByteArrayElements(barr, ba, 0);
    }
    env->DeleteLocalRef(strencode);
    env->DeleteLocalRef(clsstring);
    return rtn;
}

字节数组转char

unsigned char *jbyteArr_2unsigchar(JNIEnv *e, jbyteArray pJbyteArray) {
    unsigned char *rtn = nullptr;
    if (pJbyteArray == nullptr) {
        return nullptr;
    }
    jsize alen = e->GetArrayLength(pJbyteArray);
    jbyte *ba = e->GetByteArrayElements(pJbyteArray, JNI_FALSE);
    if (alen > 0) {
        //返回一个指针 ,指向已分配大小的内存
        rtn = (unsigned char *) malloc(alen + 1);
        memcpy(rtn, ba, alen);
        rtn[alen] = 0;
    }
    e->ReleaseByteArrayElements(pJbyteArray, ba, 0);
    return rtn;
}

以上为总结的字节间转化实现方法

你可能感兴趣的:(c语言)