Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,123 questions

55,997 answers

573 users

How to convert binary digits to a slice of bytes in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "strconv"
)

// binaryToByteArray converts a binary string to a slice of bytes
func binaryToByteArray(binaryString string) ([]byte, error) {
    if len(binaryString)%8 != 0 {
        return nil, fmt.Errorf("binary string length must be a multiple of 8")
    }

    var byteList []byte
    for i := 0; i < len(binaryString); i += 8 {
        byteSegment := binaryString[i : i+8]
        byteValue, err := strconv.ParseUint(byteSegment, 2, 8)
        if err != nil {
            return nil, fmt.Errorf("invalid binary segment: %s", byteSegment)
        }
        byteList = append(byteList, byte(byteValue))
    }

    return byteList, nil
}

func main() {
    binaryString := "10101110111010101110101001001011"

    byteList, err := binaryToByteArray(binaryString)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }

    fmt.Print("Byte List: ")
    for _, b := range byteList {
        fmt.Printf("%d ", b)
    }
}



/*
run:

Byte List: 174 234 234 75 

*/

 



answered Aug 4, 2025 by avibootz

Related questions

1 answer 158 views
1 answer 137 views
2 answers 194 views
1 answer 233 views
2 answers 290 views
...