Convert binary string to byte array

后端 未结 3 1215
眼角桃花
眼角桃花 2020-11-29 11:41

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

For example String b = \"0110100001101001\" How can I convert this to a <

相关标签:
3条回答
  • 2020-11-29 11:58

    Parse it to an integer in base 2, then convert to a byte array. In fact, since you've got 16 bits it's time to break out the rarely used short.

    short a = Short.parseShort(b, 2);
    ByteBuffer bytes = ByteBuffer.allocate(2).putShort(a);
    
    byte[] array = bytes.array();
    
    0 讨论(0)
  • 2020-11-29 12:00

    Assuming that your binary String can be divided by 8 without getting a rest you can use 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;
    }
    

    Don't forget to add the guava lib to your dependecies.

    In Android you should add to app gradle:

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

    And add this into project gradle:

    allprojects {
        repositories {
            mavenCentral()
        }
    }
    

    Update 1

    This post contains a solution without using Guava Lib.

    0 讨论(0)
  • 2020-11-29 12:11

    Another simple approach is:

    String b = "0110100001101001";
    byte[] bval = new BigInteger(b, 2).toByteArray();
    
    0 讨论(0)
提交回复
热议问题