Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • C

Idiom #275 Binary digits to byte array

From the string s consisting of 8n binary digit characters ('0' or '1'), build the equivalent array a of n bytes.
Each chunk of 8 binary digits (2 possible values per digit) is decoded into one byte (256 possible values).

#include <stdlib.h>
#include <string.h>
unsigned char *a = calloc(strlen(s) / 8, 1);
for(int i = 0; i < strlen(s); ++i){
  a[i / 8] |= (s[i] == '1') << (7 - i % 8);
}

If s is not 8n characters long or contains characters orher than '0' and '1', correct behavior is not guaranteed.
#include <string>
#include <vector>
using namespace std;
const size_t n = s.length() / 8;

vector<uint8_t> a(n);

for(size_t block = 0; block < n; block++)
{
    uint8_t acc = 0;
    const size_t start = block * 8;
    for(size_t offset = start; offset < start + 8; offset++)
    {
        acc = (acc << 1) + (s[offset] - '0');
    }

    a[block] = acc;
}

New implementation...
< >
programming-idioms.org