Convert binary string to byte array

I have a string of them and zeros that I want to convert to an array of bytes.

For example String b = "0110100001101001" How can I convert this to a byte[] length 2?

+6
source share
3 answers

Divide it by an integer in base 2, and then convert it to an array of bytes. In fact, since you have 16 bits, it is time to break out of the rarely used short .

 short a = Short.parseShort(b, 2); ByteBuffer bytes = ByteBuffer.allocate(2).putShort(a); byte[] array = bytes.array(); 
+21
source

Another simple approach:

 String b = "0110100001101001"; byte[] bval = new BigInteger(b, 2).toByteArray(); 
+12
source

Assuming your binary string can be split into 8 without rest, you can use the following method:

 /** * Get an byte array by binary string * @param binaryString the string representing a byte * @return an byte array */ public static byte[] getByteByString(String binaryString){ Iterable iterable = Splitter.fixedLength(8).split(binaryString); byte[] ret = new byte[Iterables.size(iterable) ]; Iterator iterator = iterable.iterator(); int i = 0; while (iterator.hasNext()) { Integer byteAsInt = Integer.parseInt(iterator.next().toString(), 2); ret[i] = byteAsInt.byteValue(); i++; } return ret; } 

Remember to add guava lib to your dependencies.

On Android, you should add gradle to the application:

 compile group: 'com.google.guava', name: 'guava', version: '19.0' 

And add this to your gradle project:

 allprojects { repositories { mavenCentral() } } 

Update 1

This post contains a solution without using Guava Lib.

0
source

Source: https://habr.com/ru/post/949756/


All Articles