Android String to Byte Array Convert bytesStorage(String str)

Here you can find the source of bytesStorage(String str)

Description

bytes Storage

License

Apache License

Parameter

Parameter Description
str a string

Return

the number of bytes required to represent this string in UTF-8

Declaration

public static int bytesStorage(String str) 

Method Source Code

//package com.java2s;
/*//from   w  w  w.j av a  2 s  .  c om
 * Copyright (C) 2000 Google Inc.
 *
 * 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.
 */

public class Main {
    /**
     * @param str a string
     * @return the number of bytes required to represent this string in UTF-8
     */
    public static int bytesStorage(String str) {
        // offsetByCodePoint has a bug if its argument is the result of a
        // call to substring. To avoid this, we create a new String
        // See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6242664
        String s = new String(str);

        int len = 0;
        for (int i = 0; i < s.length(); i = s.offsetByCodePoints(i, 1)) {
            len += bytesUtf8(s.codePointAt(i));
        }
        return len;
    }

    /**
     * @param c one codePoint
     * @return the number of bytes needed to encode this codePoint in UTF-8
     */
    private static int bytesUtf8(int c) {
        if (c < 0x80) {
            return 1;
        } else if (c < 0x00800) {
            return 2;
        } else if (c < 0x10000) {
            return 3;
        } else if (c < 0x200000) {
            return 4;

            // RFC 3629 forbids the use of UTF-8 for codePoint greater than 0x10FFFF,
            // so if the caller respects this RFC, this should not happen
        } else if (c < 0x4000000) {
            return 5;
        } else {
            return 6;
        }
    }
}

Related

  1. toByte(String hexString)
  2. toByte(String hexString)
  3. toBytes(final String str)
  4. StringtoByte(String data)
  5. getLengthByByte(String str)
  6. bytesStorage(String str)
  7. getBytes(String s)
  8. getBytes(String data)
  9. getBytes(String data, String charsetName)