A method to get the number of byte to represent the next character for a sequence utf-8 encoded string - Java XML

Java examples for XML:XML Encoding

Description

A method to get the number of byte to represent the next character for a sequence utf-8 encoded string

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte b = 2;
        System.out.println(getBytesforUTF8(b));
    }/*from  ww  w.  ja  v a 2s  .com*/

    /**
     * A method to get the number of byte to represent the next character for a sequence utf-8 encoded string
     * @param byte b, the first byte of utf-8 sequence
     * @return int , bytes for the consequence to represent utf-8
     */
    static public int getBytesforUTF8(byte b) {

        int ret;
        byte template = (byte) 0x40;
        for (ret = 2; ret < 7; ++ret) {
            template = (byte) (template >> 1);
            if ((b & template) == 0) {
                break;
            }
            //System.out.println(ret+" "+((b&template)==0));
        }
        return (ret);
    }
}

Related Tutorials