Java ASCII from toAsciiString(String s)

Here you can find the source of toAsciiString(String s)

Description

to Ascii String

License

Open Source License

Declaration

public static String toAsciiString(String s) 

Method Source Code

//package com.java2s;
/*//from ww  w. j  a  va  2  s.c  om
 * Xapp (pronounced Zap!), A automatic gui tool for Java.
 * Copyright (C) 2009 David Webber. All Rights Reserved.
 *
 * The contents of this file may be used under the terms of the GNU Lesser
 * General Public License Version 2.1 or later.
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 */

public class Main {
    public static String toAsciiString(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c > 127) {
                sb.append(toUnicodeStr(c));
            } else {
                sb.append((char) c);
            }
        }
        return sb.toString();
    }

    public static String toUnicodeStr(int i) {
        char c1 = Integer.toHexString((i >> 12) & 0x0000000F).charAt(0);
        char c2 = Integer.toHexString((i >> 8) & 0x0000000F).charAt(0);
        char c3 = Integer.toHexString((i >> 4) & 0x0000000F).charAt(0);
        char c4 = Integer.toHexString((i) & 0x0000000F).charAt(0);
        return "\\u" + c1 + c2 + c3 + c4;
    }
}

Related

  1. toAsciiString(byte[] buffer)
  2. toAsciiString(byte[] buffer, int startPos, int length)
  3. toAsciiString(byte[] bytes)
  4. toASCIIString(byte[] data)
  5. toAsciiString(byte[] output)
  6. toAsciiString(String value)
  7. toASCIIUpperCase(byte b)
  8. toASCIIUpperCase(String s)