How to convert a byte to its binary string representation

How to convert a byte to its binary string representation

For example, the bits in a byte B are 10000010, how can I assign the bits to the string strliterally, that is, str = "10000010".

byte b1 = (byte) 129;
String s1 = String.format("%8s", Integer.toBinaryString(b1 & 0xFF)).replace(‘ ‘, ‘0‘);
System.out.println(s1); // 10000001

byte b2 = (byte) 2;
String s2 = String.format("%8s", Integer.toBinaryString(b2 & 0xFF)).replace(‘ ‘, ‘0‘);
System.out.println(s2); // 00000010
public class BitsSetCount
{
    public static void main(String[] args)
    {
        int send = 8549658;

        System.out.println( "[Input] Integer value: " + send + "\n" );
        BitsSetCount.countBits(  send );
    }

    private static void countBits(int i)
    {
        System.out.println( "Integer.toBinaryString: " + Integer.toBinaryString(i) );
        System.out.println( "Integer.toHexString: " + Integer.toHexString(i) );
        System.out.println( "Integer.bitCount: "+ Integer.bitCount(i) );

        int d = i & 0xff000000;
        int c = i & 0xff0000;
        int b = i & 0xff00;
        int a = i & 0xff;

        System.out.println( "\nByte 4th Hex Str: " + Integer.toHexString(d) );
        System.out.println( "Byte 3rd Hex Str: " + Integer.toHexString(c) );
        System.out.println( "Byte 2nd Hex Str: " + Integer.toHexString(b) );
        System.out.println( "Byte 1st Hex Str: " + Integer.toHexString(a) );

        int all = a+b+c+d;
        System.out.println( "\n(1st + 2nd + 3rd + 4th (int(s)) as Integer.toHexString: " + Integer.toHexString(all) );

        System.out.println("(1st + 2nd + 3rd + 4th (int(s)) ==  Integer.toHexString): " +
                Integer.toHexString(all).equals(Integer.toHexString(i) ) );

        System.out.println( "\nIndividual bits for each byte in a 4 byte int:");

        /*
         * Because we are sending the MSF bytes to a method
         * which will work on a single byte and print some
         * bits we are generalising the MSF bytes
         * by making them all the same in terms of their position
         * purely for the purpose of printing or analysis
         */
        System.out.print(
                    getBits( (byte) (d >> 24) ) + " " +
                    getBits( (byte) (c >> 16) ) + " " +
                    getBits( (byte) (b >> 8) ) + " " +
                    getBits( (byte) (a >> 0) )
        );

    }

    private static String getBits( byte inByte )
    {
        // Go through each bit with a mask
        StringBuilder builder = new StringBuilder();
        for ( int j = 0; j < 8; j++ )
        {
            // Shift each bit by 1 starting at zero shift
            byte tmp =  (byte) ( inByte >> j );

            // Check byte with mask 00000001 for LSB
            int expect1 = tmp & 0x01; 

            builder.append(expect1);
        }
        return ( builder.reverse().toString() );
    }

}
public static String byteToString(byte b) {
    byte[] masks = { -128, 64, 32, 16, 8, 4, 2, 1 };
    StringBuilder builder = new StringBuilder();
    for (byte m : masks) {
        if ((b & m) == m) {
            builder.append(‘1‘);
        } else {
            builder.append(‘0‘);
        }
    }
    return builder.toString();
}
public static String getByteBinaryString(byte b) {
    StringBuilder sb = new StringBuilder();
    for (int i = 7; i >= 0; --i) {
        sb.append(b >>> i & 1);
    }
    return sb.toString();
}
String byteToBinaryString(byte b){
    StringBuilder binaryStringBuilder = new StringBuilder();
    for(int i = 0; i < 8; i++)
        binaryStringBuilder.append(((0x80 >>> i) & b) == 0? ‘0‘:‘1‘);
    return binaryStringBuilder.toString();
}
时间: 2024-08-02 10:17:15

How to convert a byte to its binary string representation的相关文章

LeetCode OJ - Convert Sorted Array/List to Binary Search Tree

虚函数使用的时机 为什么虚函数不总是适用? 1. 虚函数有事会带来很大的消耗: 2. 虚函数不总是提供所需的行为: 3. 当我们不考虑继承当前类时,不必使用虚函数. 必须使用虚函数的情况: 1. 当你想删除一个表面上指向基类对象,实际却是指向派生类对象的指针,就需要虚析构函数. LeetCode OJ - Convert Sorted Array/List to Binary Search Tree,布布扣,bubuko.com LeetCode OJ - Convert Sorted Arra

C# Tips: String Convert to byte[]

string s = "test"; //Convert from string to byte[] //byte[] bytes = Convert.FromBase64String(s); byte[] bytes = Encoding.UTF8.GetBytes(s); //Convert from byte[] to String //string s2 = Convert.ToBase64String(bytes); string s2 = Encoding.UTF8.Get

108.&#160;Convert Sorted Array to balanced Binary Search Tree

108. Convert Sorted Array to balanced Binary Search Tree The tricky part is the base case . Write induction part first and then test arrays of different size, 0, 1,2, 3 And finalize the base case /** * Definition for a binary tree node. * public clas

Byte Array to Hexadecimal String

Lookup Text: 23,879.41 (20.8X faster) Sentence: 1.15 (23.9X faster) /// <summary> /// Hex string lookup table. /// </summary> private static readonly string[] HexStringTable = new string[] { "00", "01", "02", &quo

NYOJ 5 Binary String Matching【string find的运用】

Binary String Matching 时间限制:3000 ms  |  内存限制:65535 KB 难度:3 描述 Given two strings A and B, whose alphabet consist only '0' and '1'. Your task is only to tell how many times does A appear as a substring of B? For example, the text string B is '100111011

NYOJ5 Binary String Matching

Binary String Matching 时间限制:3000 ms  |  内存限制:65535 KB 难度:3 描述 Given two strings A and B, whose alphabet consist only ‘0’ and ‘1’. Your task is only to tell how many times does A appear as a substring of B? For example, the text string B is ‘100111011

NYOJ 5 Binary String Matching (kmp 字符串匹配)

Binary String Matching 时间限制:3000 ms  |  内存限制:65535 KB 难度:3 描述 Given two strings A and B, whose alphabet consist only '0' and '1'. Your task is only to tell how many times does A appear as a substring of B? For example, the text string B is '100111011

NYOJ 5 Binary String Matching

Binary String Matching 时间限制:3000 ms  |  内存限制:65535 KB 难度:3 描述 Given two strings A and B, whose alphabet consist only ‘0’ and ‘1’. Your task is only to tell how many times does A appear as a substring of B? For example, the text string B is ‘100111011

nyoj5 Binary String Matching(KMP)

Binary String Matching 时间限制:3000 ms  |  内存限制:65535 KB 难度:3 描述 Given two strings A and B, whose alphabet consist only '0' and '1'. Your task is only to tell how many times does A appear as a substring of B? For example, the text string B is '100111011