Here you can find the source of validBytesUTF8(ByteBuffer buf, int offset, int limit)
public static boolean validBytesUTF8(ByteBuffer buf, int offset, int limit)
//package com.java2s; /**// w ww . j av a2s . c o m * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import static java.lang.String.format; import java.nio.ByteBuffer; public class Main { public static boolean validBytesUTF8(byte[] input) { for (int index = 0; index < input.length;) { byte leadingByte = input[index++]; if ((leadingByte & 0xc0) == 0x80) { return false; } int remaining = remainingBytesUTF8(leadingByte); switch (remaining) { case 0: break; default: while (remaining-- > 0) { if ((input[index++] & 0xc0) != 0x80) { return false; } } } } return true; } public static boolean validBytesUTF8(ByteBuffer buf, int offset, int limit) { for (int index = offset; index < limit;) { byte leadingByte = buf.get(index++); if ((leadingByte & 0xc0) == 0x80) { return false; } int remaining = remainingBytesUTF8(leadingByte); switch (remaining) { case 0: break; default: while (remaining-- > 0) { if ((buf.get(index++) & 0xc0) != 0x80) { return false; } } } } return true; } public static int remainingBytesUTF8(int leadingByte) { if ((leadingByte & 0x80) == 0) { return 0; } for (byte i = 0; i < 7; i++) { int bitMask = 1 << (7 - i); if ((leadingByte & bitMask) != 0) { continue; } else { switch (i) { case 0: case 7: throw new IllegalStateException( format("Invalid UTF-8 sequence leader byte: 0x%02x", leadingByte)); default: return i - 1; } } } throw new IllegalStateException(String.format("Invalid UTF-8 sequence leader byte: 0x%02x", leadingByte)); } }