📜  Java中的 UTF-8 验证

📅  最后修改于: 2022-05-13 01:54:58.506000             🧑  作者: Mango

Java中的 UTF-8 验证

UTF-8中的字符可以是 1 到 4 个字节长,遵循以下规则:

  1. 对于 1 字节字符,第一位是 0,后跟其 Unicode 代码。
  2. 对于 n 字节字符,前 n 位都是 1,n+1 位为 0,然后是 n-1 个字节,最高有效 2 位为 10。

这是 UTF-8 编码的工作方式:

Char. number range   |        UTF-8 octet sequence
      (hexadecimal)    |              (binary)
   --------------------+---------------------------------------------
   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 编码。

输入是一个整数数组。只有每个整数的最低有效 8 位用于存储数据。这意味着每个整数仅代表 1 个字节的数据。

方法:只要数组中的每个字节都是正确的类型,它就是有效的 UTF-8 编码。  

  • 从索引 0 开始,确定每个字节的类型并检查其有效性。
  • 有效字节类型有五种:0**、10**、110**、1110**和11110**
  • 给他们输入类型数字 0, 1, 2, 3, 4,它们是左起第一个 0 的索引。
  • 因此,第一个 0 的索引决定了字节类型。
  • 如果一个字节属于其中之一:如果是类型0,如果是类型2或3或4,则继续,检查以下1、2和3个字节是否为类型1。
  • 如果不是,返回false;否则,如果字节类型为 1 或不是有效类型,则返回 false。
Java
// Java program to check whether the data
// is a valid UTF-8 encoding
  
import java.io.*;
import java.util.*;
  
class Sol {
  
    private int[] masks = { 128, 64, 32, 16, 8 };
  
    public boolean validUtf8(int[] data)
    {
        int len = data.length;
  
        // for each value in the data array we have to take
        // the "and" with the masks array
        for (int i = 0; i < len; i++) {
            int curr = data[i];
  
            // method to check the array if the
            // and with the num and masks array is
            // 0 then return true
            int type = getType(curr);
  
            if (type == 0) {
                continue;
            }
  
            else if (type > 1 && i + type <= len)
            {
                while (type-- > 1) 
                {
                    if (getType(data[++i]) != 1)
                    {
                        return false;
                    }
                }
            }
            else {
                return false;
            }
        }
        return true;
    }
  
    // method to check the type
    public int getType(int num)
    {
        for (int i = 0; i < 5; i++) {
  
            // checking the each input
            if ((masks[i] & num) == 0) {
                return i;
            }
        }
  
        return -1;
    }
}
  
class GFG {
    public static void main(String[] args)
    {
        Sol st = new Sol();
        int[] arr = { 197, 130, 1 };
  
        boolean res = st.validUtf8(arr);
        System.out.println(res);
    }
}


输出
true
  • 时间复杂度: O(n)
  • 空间复杂度: O(1)