Logo

Programming-Idioms

  • Java
  • Python

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

import re
p = re.findall('.{8}', s)
a = [*map(lambda x: int(x, 2), p)]
from re import findall
p = findall('.{8}', s)
a = bytes(int(x, 2) for x in p)
n = (len(s) - 1) // 8 + 1
a = bytearray(n)
for i in range(n):
    b = int(s[i * 8:(i + 1) * 8], 2)
    a[i] = b
f = lambda x: int(s[x:x + 8], 2)
a = [*map(f, range(0, len(s), 8))]
from itertools import batched
f = lambda x: int(''.join(x), 2)
a = [*map(f, batched(s, 8))]

The `batched` function is from Python 3.12+.
import static java.lang.Integer.parseInt;
int i, m = s.length(), n = (m + 1) / 8, t;
byte a[] = new byte[n];
for (i = 0; i < m; i = i + 8) {
    t = parseInt(s.substring(i, i + 8), 2);
    a[i / 8] = (byte) t;
}
#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