如何将字节转换为二进制字符串表示形式

时间:2012-09-06 23:56:08

标签: java binary byte

例如,字节B中的位是10000010,如何将字符串str字节分配给str = "10000010",即B

修改

我从二进制文件中读取字节,并存储在字节数组System.out.println(Integer.toBinaryString(B[i]))中。我使用B[i]。问题是

(a)当位以(最左边)1开始时,输出不正确,因为它将0转换为负int值。

(b)如果位以0开头,则输出忽略B[0],例如,假设1具有00000001,输出为00000001而不是{{ 1}}

14 个答案:

答案 0 :(得分:148)

使用Integer#toBinaryString()

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

<强> DEMO

答案 1 :(得分:26)

我用过这个。与其他答案类似的想法,但没有看到任何地方的确切方法:)

System.out.println(Integer.toBinaryString((b & 0xFF) + 0x100).substring(1));

0xFF为255,或11111111(无符号字节的最大值)。 0x100为256,或100000000

&将字节向上转换为整数。此时,它可以是0 - 2550000000011111111之间的任何内容,我排除了前24位)。 + 0x100.substring(1)确保会有前导零。

我将它与João Silva's answer进行了比较,并且速度提高了10倍以上。 http://ideone.com/22DDK1我没有包含Pshemo的答案,因为它没有正确填充。

答案 2 :(得分:7)

这是你在找什么?

从String转换为byte

byte b = (byte)(int)Integer.valueOf("10000010", 2);
System.out.println(b);// output -> -126

从字节转换为字符串

System.out.println(Integer.toBinaryString((b+256)%256));// output -> "10000010"

或者正如JoãoSilva在评论中添加前导0时我们可以将字符串格式化为长度8并将结果前导空格替换为零,因此对于像" 1010"这样的字符串,我们将获得{{ 1}}

"00001010"

答案 3 :(得分:3)

您可以检查字节上的每个位,然后将0或1附加到字符串。这是我为测试编写的一个小助手方法:

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();
}

答案 4 :(得分:2)

此代码将演示如何将java int拆分为4个连续的字节。 然后,我们可以使用Java方法检查每个字节,与低级字节/位询问相比。

这是运行以下代码时的预期输出:

[Input] Integer value: 8549658

Integer.toBinaryString: 100000100111010100011010
Integer.toHexString: 82751a
Integer.bitCount: 10

Byte 4th Hex Str: 0
Byte 3rd Hex Str: 820000
Byte 2nd Hex Str: 7500
Byte 1st Hex Str: 1a

(1st + 2nd + 3rd + 4th (int(s)) as Integer.toHexString: 82751a
(1st + 2nd + 3rd + 4th (int(s)) ==  Integer.toHexString): true

Individual bits for each byte in a 4 byte int:
00000000 10000010 01110101 00011010

以下是要运行的代码:

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() );
    }

}

答案 5 :(得分:2)

获取每个字节并转换为字符串。 假设字节有8位,我们可以通过位移逐个获取它们。例如,我们将字节6位的第二位移到右边,第二位移到最后一位8位,然后和(&amp;)移位0x0001来清理前面的位。

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();
}

答案 6 :(得分:2)

抱歉,我知道这有点晚了...但我有一个更简单的方法...... 二进制字符串:

//Add 128 to get a value from 0 - 255
String bs = Integer.toBinaryString(data[i]+128);
bs = getCorrectBits(bs, 8);

getCorrectBits方法:

private static String getCorrectBits(String bitStr, int max){
    //Create a temp str to add all the zeros
    String tmpStr = "";
    for(int i = 0; i < (max - bitStr.length()); i ++){
        tmpStr += "0";
    }

    return tmpStr + bitStr;
}

答案 7 :(得分:2)

Integer.toBinaryString((byteValue & 0xFF) + 256).substring(1)

答案 8 :(得分:1)

\n

答案 9 :(得分:1)

您可以像下面的示例一样使用 BigInteger ,尤其是如果您具有 256位或更长的时间:

String string = "10000010";
BigInteger biStr = new BigInteger(string, 2);

System.out.println("binary: " + biStr.toString(2));
System.out.println("hex: " + biStr.toString(16));
System.out.println("dec: " + biStr.toString(10));

另一个接受字节的示例:

String string = "The girl on the red dress.";

byte[] byteString = string.getBytes(Charset.forName("UTF-8"));
System.out.println("[Input String]: " + string);
System.out.println("[Encoded String UTF-8]: " + byteString);

BigInteger biStr = new BigInteger(byteString);
System.out.println("binary: " + biStr.toString(2)); // binary
System.out.println("hex: " + biStr.toString(16));   // hex or base 16
System.out.println("dec: " + biStr.toString(10));  // this is base 10

结果:

[Input String]: The girl on the red dress.
[Encoded String UTF-8]: [B@70dea4e

binary: 101010001101000011001010010000001100111011010010111001001101100001000000110111101101110001000000111010001101000011001010010000001110010011001010110010000100000011001000111001001100101011100110111001100101110
hex: 546865206769726c206f6e20746865207265642064726573732e

您还可以将二进制转换为 Byte 格式

try {
   System.out.println("binary to byte: " + biStr.toString(2).getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {e.printStackTrace();}

注意: 对于二进制格式的字符串格式,可以使用以下示例

String.format("%256s", biStr.toString(2).replace(' ', '0'));  // this is for the 256 bit formatting

答案 10 :(得分:1)

一个简单的答案可能是:

System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})); // 0
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1})); // 1
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0})); // 256
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0})); // 65536
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0})); // 16777216
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0})); // 4294967296
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0})); // 1099511627776
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0})); // 281474976710656
System.out.println(new BigInteger(new byte[]{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0})); // 72057594037927936
System.out.println(new BigInteger(new byte[]{0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0})); // 18446744073709551616
System.out.println(new BigInteger(new byte[]{0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0})); // 4722366482869645213696
System.out.println(new BigInteger(new byte[]{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})); // 1208925819614629174706176
System.out.println(Long.MAX_VALUE);                                              // 9223372036854775807

答案 11 :(得分:0)

我们都知道Java不提供unsigned关键字之类的东西。此外,根据Java规范的byte原语表示−128127之间的值。例如,如果bytecast的{​​{1}},Java会将第一个int解释为bit并使用符号扩展名。

然后,如何将大于sign的字节转换为其二进制字符串表示形式?

没有什么可以阻止您仅以8位查看127并将这些位解释为byte0之间的值。另外,您需要记住,您无能为力以其他人的方法进行解释。如果方法接受255,则该方法接受byte−128之间的值,除非另有明确说明。

因此解决此问题的最佳方法是通过调用127方法或将其强制转换为byte原语{{1}将int值转换为Byte.toUnsignedInt()值}}。这里有一个示例:

int

输出

(int) signedByte & 0xFF

答案 12 :(得分:0)

对于那些需要将字节大量转换为二进制字符串的人来说,这是另一个提示:使用查找表而不是一直使用这些String操作。这比一次又一次地调用convert函数要快得多

public class ByteConverterUtil {

  private static final String[] LOOKUP_TABLE = IntStream.range(0, Byte.MAX_VALUE - Byte.MIN_VALUE + 1)
                                                        .mapToObj(intValue -> Integer.toBinaryString(intValue + 0x100).substring(1))
                                                        .toArray(String[]::new);

  public static String convertByte(final byte byteValue) {
    return LOOKUP_TABLE[Byte.toUnsignedInt(byteValue)];
  }

  public static void main(String[] args){
    System.out.println(convertByte((byte)0)); //00000000
    System.out.println(convertByte((byte)2)); //00000010
    System.out.println(convertByte((byte)129)); //10000001
    System.out.println(convertByte((byte)255)); //11111111
  }


}

答案 13 :(得分:-1)

只是在这里猜测,但是如果你有一个Byte那么你不能简单地在对象上调用toString()来获取值吗?或者,使用byteValue()?

浏览api