Java Byte Array Convert To bytesToAsciiMaybe(byte[] data)

Here you can find the source of bytesToAsciiMaybe(byte[] data)

Description

bytes To Ascii Maybe

License

Open Source License

Declaration

public static String bytesToAsciiMaybe(byte[] data) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    public static int PRINTABLE_ASCII_MIN = 0x20;
    public static int PRINTABLE_ASCII_MAX = 0x7E;

    public static String bytesToAsciiMaybe(byte[] data) {
        return bytesToAsciiMaybe(data, 0, data.length);
    }//  w  ww .  j  av a 2  s  .c  o m

    public static String bytesToAsciiMaybe(byte[] data, int offset, int length) {
        StringBuilder ascii = new StringBuilder();
        boolean zeros = false;
        for (int i = offset; i < offset + length; i++) {
            int c = data[i] & 0xFF;
            if (isPrintableAscii(c)) {
                if (zeros) {
                    return null;
                }
                ascii.append((char) c);
            } else if (c == 0) {
                zeros = true;
            } else {
                return null;
            }
        }
        return ascii.toString();
    }

    public static boolean isPrintableAscii(int c) {
        return c >= PRINTABLE_ASCII_MIN && c <= PRINTABLE_ASCII_MAX;
    }
}

Related

  1. Bytes8ToLong(byte abyte0[], int offset)
  2. bytes_to_sbuf(byte[] data, int offset, int length, StringBuffer buf)
  3. bytes_to_short(byte[] buf, int offset)
  4. bytes_to_str(byte[] data)
  5. bytesToAlphaNumeric(byte[] number)
  6. bytesToBlocks(final long bytes, final int blockSize)
  7. bytesToBool(byte[] data, int[] offset)
  8. bytesToBoxingBytes(final byte[] bytes)
  9. BytesTobytes(Byte[] bytes)