print Binary - Java java.lang

Java examples for java.lang:int Binary

Description

print Binary

Demo Code

/*******************************************************************************
 * Copyright (c) 2004, 2007 Boeing.//  w w w.j  a v a2  s .  c o  m
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Boeing - initial API and implementation
 *******************************************************************************/
import java.io.PrintStream;
import java.nio.ByteBuffer;

public class Main{
    public static void printBinary(byte[] data, int bytesPerGroup,
            int groupPerLine, PrintStream out) {
        int groups = 0;
        for (int i = 0; i < data.length; i++) {
            out.print(ByteUtil.toBinaryString(data[i]));
            if ((i + 1) % bytesPerGroup == 0) {
                out.print(" ");
                groups++;
                if (groups % groupPerLine == 0) {
                    out.println();
                }
            }
        }
    }
    /**
     * NOTE the SDK supplies a Integer.toBinaryString but it is not formatted to a standard number of chars so it was not
     * a good option.
     */
    public static String toBinaryString(byte b) {
        StringBuffer sb = new StringBuffer();
        sb.append((b >> 7 & 0x01));
        sb.append((b >> 6 & 0x01));
        sb.append((b >> 5 & 0x01));
        sb.append((b >> 4 & 0x01));
        sb.append((b >> 3 & 0x01));
        sb.append((b >> 2 & 0x01));
        sb.append((b >> 1 & 0x01));
        sb.append((b & 0x01));
        return sb.toString();
    }
}

Related Tutorials