1 Star 79 Fork 34

John-逍遥/android_plugin_readme

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
README_unicode_conversion.md 9.12 KB
一键复制 编辑 原始数据 按行查看 历史
John-逍遥 提交于 4年前 . 更新插件

中文 Unicode 互转 代码展示

以下只展示关键部分

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

   ...

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:text="中文:"/>
        <EditText
            android:id="@+id/edit_text_a"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#333333"
            android:textColorHint="#999999"
            android:hint="例如:我是中国人"
            android:singleLine="true"
            android:background="#00000000"
            />
        <View
            android:id="@+id/underline1"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginTop="1dp"
            tools:background="@color/theme_color"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:layout_marginTop="10dp"
            android:text="Unicode 编码:"/>
        <EditText
            android:id="@+id/edit_text_b"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#333333"
            android:textColorHint="#999999"
            android:singleLine="true"
            android:hint="例如:\u6211\u5f88\u5389\u5bb3"
            android:background="#00000000"
            />
        <View
            android:id="@+id/underline2"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginTop="1dp"
            tools:background="@color/theme_color"
            />
        <Button
            android:id="@+id/btEncode"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#333333"
            android:textAllCaps="false"
            android:text="中文转 Unicode"/>

        <Button
            android:id="@+id/btDecode"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#333333"
            android:textAllCaps="false"
            android:text="Unicode 转中文"/>
    </LinearLayout>
</LinearLayout>
MainActivity.kt
package com.lujianfei.plugin7_4

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import com.lujianfei.module_plugin_base.base.BasePluginActivity
import com.lujianfei.module_plugin_base.beans.PluginActivityBean


class MainActivity : BasePluginActivity() {
    companion object {
        const val TAG = "MainActivity"
    }

    ...
    private var edit_text_a: EditText? = null
    private var edit_text_b: EditText? = null
    private var underline1: View? = null
    private var underline2: View? = null
    private var btDecode: View? = null
    private var btEncode: View? = null

    override fun resouceId(): Int = R.layout.activity_main

    override fun initView() {
        btEncode = findViewById(R.id.btEncode)
        btDecode = findViewById(R.id.btDecode)
        underline1 = findViewById(R.id.underline1)
        underline2 = findViewById(R.id.underline2)
        edit_text_a = findViewById(R.id.edit_text_a)
        edit_text_b = findViewById(R.id.edit_text_b)
       ...
    }

   ...

    override fun initEvent() {
       ...
        btEncode?.setOnClickListener {
            encodeClick()
        }
        btDecode?.setOnClickListener {
            decodeClick()
        }
    }

    private fun encodeClick() {
        edit_text_a?.let { edittext ->
            if (edittext.text.isEmpty()) {
                edittext.error = "中文不能为空"
                return
            }
            edittext.text?.let {text->
                edit_text_b?.setText(StringHelper.chineseToUnicode(text.toString()))    
            }
        }
    }

    private fun decodeClick() {
        edit_text_b?.let { edittext ->
            if (edittext.text.isEmpty()) {
                edittext.error = "Unicode 编码不能为空"
                return
            }
            edittext.text?.let {text->
                kotlin.runCatching {
                    edit_text_a?.setText(StringHelper.unicodeToChinese(text.toString()))       
                }.onFailure {
                    edittext.error = "Unicode 编码格式有误"
                }
            }
        }
    }

   ...
}

StringHelper.kt
package com.lujianfei.plugin7_4

import java.nio.charset.Charset

/**
 *@date     创建时间:2020/6/9
 *@name     作者:陆键霏
 *@describe 描述:
 */
object StringHelper {

    /**
     * 中文转 Unicode 
     */
    fun chineseToUnicode(str:String):String {
        val utfBytes: CharArray = str.toCharArray()
        var unicodeBytes = ""
        for (i in utfBytes.indices) {
            var hexB = Integer.toHexString(utfBytes[i].toInt())
            if (hexB.length <= 2) {
                hexB = "00$hexB"
            }
            unicodeBytes = "$unicodeBytes\\u$hexB"
        }
        return unicodeBytes
    }

    /**
     * Unicode 转 中文
     */
    fun unicodeToChinese(str:String):String {
        var start = 0
        var end = 0
        val buffer = StringBuffer()
        while (start > -1) {
            end = str.indexOf("\\u", start + 2)
            var charStr = ""
            charStr = if (end == -1) {
                str.substring(start + 2, str.length)
            } else {
                str.substring(start + 2, end)
            }
            val letter = charStr.toInt(16).toChar() // 16进制parse整形字符串。
            buffer.append(letter.toString())
            start = end
        }
        return buffer.toString()
    }

    /**
     * 中文转 UTF-8
     */
    fun chineseToUtf8(str:String):String {
        var unicodeBytes = ""
        for (element in str) {
            val s = element.toString().toByteArray(Charset.forName("utf-8"))
            unicodeBytes = "$unicodeBytes\\u"
            for (i in s.indices) {
                var hexB = Integer.toHexString(s[i].toInt().and(0xff))
                if (hexB.length <= 1) {
                    hexB = "0$hexB"
                }
                unicodeBytes = "$unicodeBytes$hexB"
            }
        }
        return unicodeBytes
    }

    /**
     * Utf8 转 中文
     */
    fun utf8ToChinese(str:String):String {
        var start = 0
        var end = 0
        val buffer = StringBuffer()
        while (start > -1) {
            end = str.indexOf("\\u", start + 2)
            var charStr = ""
            charStr = if (end == -1) {
                str.substring(start + 2, str.length)
            } else {
                str.substring(start + 2, end)
            }
            buffer.append(String(hexStringToBytes(charStr), Charset.forName("utf-8")))
            start = end
        }
        return buffer.toString()
    }

    private fun hexStringToBytes(hexstring: String): ByteArray {
        val size = hexstring.length / 2
        val bytes = ByteArray(size)
        var j = 0
        for (i in 0 until size) {
            val high = (Character.digit(hexstring[j], 16).and(0xff))
            val low = (Character.digit(hexstring[j + 1], 16).and(0xff))
            bytes[i] = high.shl(4).or(low).toByte()
            j += 2
        }
        return bytes
    }
}
关注 unicode 和 utf8 编码
Unicode符号范围 | UTF-8编码方式

(十六进制) | (二进制)
—————————————————————–
0000 0000-0000 007F | 0xxxxxxx

0000 0080-0000 07FF | 110xxxxx 10xxxxxx

0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx

0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

跟据上表,解读UTF-8编码非常简单。如果一个字节的第一位是0,则这个字节单独就是一个字符;如果第一位是1,则连续有多少个1,就表示当前字符占用多少个字节。下面,还是以汉字"严"为例,演示如何实现UTF-8编码。

已知"严"的unicode是4E25(100111000100101),根据上表,可以发现4E25处在第三行的范围内(0000 0800-0000 FFFF),因此"严"的UTF-8编码需要三个字节,即格式是"1110xxxx 10xxxxxx 10xxxxxx"。然后,从"严"的最后一个二进制位开始,依次从后向前填入格式中的x,多出的位补0。这样就得到了,"严"的UTF-8编码是"11100100 10111000 10100101",转换成十六进制就是E4B8A5。
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Android
1
https://gitee.com/lujianfei/android_plugin_readme.git
git@gitee.com:lujianfei/android_plugin_readme.git
lujianfei
android_plugin_readme
android_plugin_readme
master

搜索帮助