How to convert binary digits to a byte list in Java

1 Answer

0 votes
import java.util.ArrayList;
import java.util.List;

public class BinaryConverter {

    public static List<Byte> binaryToByteArray(String binaryString) {
        List<Byte> byteArray = new ArrayList<>();

        // Ensure the binary string length is a multiple of 8
        if (binaryString.length() % 8 != 0) {
            throw new IllegalArgumentException("Binary string length must be a multiple of 8.");
        }

        // Process each 8-bit chunk
        for (int i = 0; i < binaryString.length(); i += 8) {
            String byteString = binaryString.substring(i, i + 8);
            byte byteValue = (byte) Integer.parseInt(byteString, 2);
            byteArray.add(byteValue);
        }

        return byteArray;
    }

    public static void main(String[] args) {
        String binaryString = "10101110111010101110101001001011";

        try {
            List<Byte> byteArray = binaryToByteArray(binaryString);

            System.out.print("Byte Array: ");
            for (byte b : byteArray) {
                // Convert to unsigned int for display
                System.out.print((b & 0xFF) + " ");
            }
            System.out.println();
        } catch (IllegalArgumentException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}



/*
run:
  
Byte Array: 174 234 234 75 

*/


 



answered Aug 4, 2025 by avibootz
...