How to convert binary digits to a byte list in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

class BinaryConverter
{
    public static List<byte> BinaryToByteList(string binaryString) {
        var byteList = new List<byte>();

        // Ensure the binary string length is a multiple of 8
        if (binaryString.Length % 8 != 0) {
            throw new ArgumentException("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, 8);
            byte byteValue = Convert.ToByte(byteString, 2);
            byteList.Add(byteValue);
        }

        return byteList;
    }

    static void Main()
    {
        string binaryString = "10101110111010101110101001001011";

        try
        {
            List<byte> byteList = BinaryToByteList(binaryString);

            Console.Write("Byte List: ");
            foreach (byte b in byteList) {
                Console.Write($"{b} ");
            }
            Console.WriteLine();
        }
        catch (Exception e)
        {
            Console.Error.WriteLine($"Error: {e.Message}");
        }
    }
}



/*
run:
  
Byte List: 174 234 234 75 

*/

 



answered Aug 4, 2025 by avibootz
edited Aug 4, 2025 by avibootz

Related questions

...