集册 Java实例教程 将字节转换为长度为8的字符串,由0和1组成,这些0和1对应于字节的二进制表示形式

将字节转换为长度为8的字符串,由0和1组成,这些0和1对应于字节的二进制表示形式

欢马劈雪     最近更新时间:2020-01-02 10:19:05

410
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
将字节转换为长度为8的字符串,由0和1组成,这些0和1对应于字节的二进制表示形式
/*
 from n o w j a v a . c o m 
*/


//package com.nowjava;


public class Main {

    public static void main(String[] argv) throws Exception {

        byte b = 2;

        System.out.println(bitStringFromByte(b));

    }


    /**

     * Converts a byte into a String of length 8, consisting of 0s and 1s that

     * corresponds to the binary representation of the byte

     *

     * @param b byte to convert

     * @return String of 0's and 1's that is the binary representation of b

     */

    public static String bitStringFromByte(byte b) {

        String tail = Integer.toBinaryString(b & 0xFF).replace(' ', '0');

        int tailLen = tail.length();

        
展开阅读全文