Java Convert via ByteBuffer toByteArray(String bits)

Here you can find the source of toByteArray(String bits)

Description

to Byte Array

License

LGPL

Declaration

public static byte[] toByteArray(String bits) 

Method Source Code


//package com.java2s;
//License from project: LGPL 

import java.nio.ByteBuffer;

public class Main {
    public static byte[] toByteArray(double value) {
        byte[] bytes = new byte[8];
        ByteBuffer.wrap(bytes).putDouble(value);
        return bytes;
    }//  www. j  av a2  s  . c  o m

    public static byte[] toByteArray(String bits) {
        int byteLength = bits.length() / 8;
        if (bits.length() % 8 != 0) {
            byteLength += 1;
        }
        byte[] bytes = new byte[byteLength];
        for (int i = 0; i < bits.length(); i++) {
            setBit(bytes, i, (byte) (bits.charAt(i) == '1' ? 1 : 0));
        }
        return bytes;
    }

    public static void setBit(byte[] data, long pos, byte val) {
        int posByte = (int) (pos / 8);
        int posBit = (int) (pos % 8);
        byte oldByte = data[posByte];
        data[posByte] = setBit(oldByte, posBit, val);
    }

    public static byte setBit(byte data, long pos, byte val) {
        data = (byte) (((0xFF7F >> pos) & data) & 0x00FF);
        return (byte) ((val << (8 - (pos + 1))) | data);
    }
}

Related

  1. toByteArray(int[] data, boolean bigEndian)
  2. toByteArray(int[] intArray)
  3. toByteArray(long[] data)
  4. ToByteArray(long[] data)
  5. toByteArray(ReadableByteChannel channel)
  6. ToByteArray(String hexString)
  7. toByteArray(String value)
  8. toByteArray(UUID uniqueId)
  9. toByteArray2(String filename)