Extract a UCS-2BE string from the specified buffer (buf) starting at position off, ending at position off+len - Java java.lang

Java examples for java.lang:String UTF

Description

Extract a UCS-2BE string from the specified buffer (buf) starting at position off, ending at position off+len

Demo Code


import java.io.*;
import java.util.Vector;

public class Main{
    /**//from   ww w  .  java2 s .com
     * Extract a UCS-2BE string from the specified buffer (buf)
     * starting at position off, ending at position off+len
     */
    public static String ucs2beByteArrayToString(byte[] buf, int off,
            int len) {

        // Length check
        if ((off + len > buf.length) || (len % 2 != 0)) {
            return "";
        }

        // Convert
        StringBuilder sb = new StringBuilder();
        int end = off + len;
        for (int i = off; i < end; i += 2) {
            sb.append((char) Util.getWordBE(buf, i));
        }
        return removeCr(sb.toString());

    }
    public static String removeCr(String val) {
        if (val.indexOf('\r') < 0) {
            return val;
        }
        if (-1 == val.indexOf('\n')) {
            return val.replace('\r', '\n');
        }

        StringBuilder result = new StringBuilder();
        int size = val.length();
        for (int i = 0; i < size; ++i) {
            char chr = val.charAt(i);
            if ((chr == 0) || (chr == '\r'))
                continue;
            result.append(chr);
        }
        return result.toString();
    }
}

Related Tutorials