Java Bit String From toBitString(byte[] bytes)

Here you can find the source of toBitString(byte[] bytes)

Description

to Bit String

License

Apache License

Declaration

public static String toBitString(byte[] bytes) 

Method Source Code

//package com.java2s;
/*/*from w  w  w  .ja v  a2s.c  o  m*/
 * Copyright 2012 Shoji Nishimura
 * 
 * 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 {
    public static String toBitString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        boolean skip = true;
        for (byte b : bytes) {
            if (b == 0 && skip) {
            } else {
                skip = false;
                for (int i = 7; i >= 0; i--) {
                    sb.append((b >> i) & 1);
                }
            }
        }
        return sb.toString();
    }

    public static String toString(byte[] key, int prefixLength) {
        StringBuilder buf = new StringBuilder();
        int d = (prefixLength - 1) / 8;
        int r = (prefixLength - 1) % 8;
        final int[] masks = new int[] { -128, 64, 32, 16, 8, 4, 2, 1 };
        for (int i = 0; i < d; i++) {
            for (int j = 0; j < masks.length; j++) {
                buf.append((key[i] & masks[j]) == 0 ? "0" : "1");
            }
        }
        for (int j = 0; j <= r; j++) {
            buf.append((key[d] & masks[j]) == 0 ? "0" : "1");
        }
        for (int j = r + 1; j < masks.length; j++) {
            buf.append("*");
        }
        for (int i = d + 1; i < key.length; i++) {
            buf.append("********");
        }
        return buf.toString();
    }
}

Related

  1. toBits(int b)
  2. toBits(int b)
  3. toBits(long value, int length)
  4. toBitsArray(byte[] bytes, int bitCount)
  5. toBitString(byte value)
  6. toBitString(byte[] bytes)
  7. toBitString(byte[] bytes, final int digitsPerGroup, final String groupSeparator)
  8. toBitString(byte[] data)
  9. toBitString(final byte n)