Logo

Programming-Idioms

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

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).

my $s = '1000' . '0010' . '0101' . '1010';   # AZ

my @a;
for ( my $i = 0; $i < length $s; $i += 8) {
    my @b = pack 'b8', substr($s, $i, 8);
    push @a, @b;
}

String var $s is assigned the concatenation of 4 nybbles (defined as strings of 1's and 0's) forming two octets representing ASCII characters A and Z. The string is parsed 8 characters at a time using substr, and each group is encoded into a byte using perl pack. Then the byte is pushed onto the @a list.
#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.

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