简体   繁体   中英

Convert Binary String to Binary

How do I convert a String written as Binary, to binary (in byte array)?

If I have a String:

String binary = "0000"

I want the binary data to be 0000 .

below is what happens when I set the binary to a byte array (which in turn returns 48, which is ASCII)

Binary String: 0000 Binary Byte array: 48 Binary Byte array: 48 Binary Byte array: 48 Binary Byte array: 48

I'm not good at explaining so hopefully the above example was enough to tell you what I want.

EDIT: This is to set the data into a binary file.

Use this:

    System.out.println(Integer.toBinaryString(Integer.parseInt("000",2))); // gives 0
    System.out.println(Integer.toBinaryString(Integer.parseInt("010",2))); // gives 10
    System.out.println(Integer.toBinaryString(Integer.parseInt("100",2))); // gives 100

Convert into Decimal from Binary

System.out.println(new BigInteger("1010",2).toString()); // 10 decimal

Convert into Binary/Octal/Hex from Decimal

You can use BigInteger#toString(radix) method to get value in any radix.

System.out.println(new BigInteger("10").toString(2));  // 1010  binary
System.out.println(new BigInteger("10").toString(8));  // 12    octal
System.out.println(new BigInteger("10").toString(16)); // a     hexadecimal

Let me explain you a bit more how it works with different base

(10) 10 = (1010) 2

(10) 10 = (12) 8

(10) 10 = (a) 16

Maybe you want this:

int i = Integer.valueOf(binary, 2); // ie base 2

This call expects the input to be a string of 0 and 1 chars.

Then if you want an array of bytes:

byte[] bytes = new ByteBuffer().putInt(i).compact().array();

JBBP框架在utils中有一个特殊的方法将包含二进制定义数据的字符串转换为字节数组

 byte [] converted = JBBPUtils.str2bin("00000000");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM